0

I'm trying to replace the token "[RANDOMNUMBER]" in a string but my code is not working? The regex shows as valid when checking on online validation tools? I know it has to be a stupid mistake but I don't see it?

function detokenizeTags(imgSrc){
    var rn = Math.random() + "",
    rnd = rn * 10000000000000;
    imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);
    return imgSrc; 
}

sample input string: //ad.amgdgt.com/ads/?t=ap&px=79079&rndn=[RANDOMNUMBER]

Michael Johns
  • 419
  • 3
  • 21

2 Answers2

1

The problem is the fact the replacement does NOT change the original string.

imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);

needs to be

imgSrc = imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);

function detokenizeTags(imgSrc){
    var rn = Math.random() + "",
    rnd = rn * 10000000000000;
    return imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);
}

var str = "//ad.amgdgt.com/ads/?t=ap&px=79079&rndn=[RANDOMNUMBER]";

console.log(str, detokenizeTags(str));
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

.replace doesn't modify the string, it returns a new string. Instead of:

imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);
return imgSrc; 

try just:

return imgSrc.replace(/\[RANDOMNUMBER\]/g,rnd);
Chris Simon
  • 6,185
  • 1
  • 22
  • 31