Michael Johns Michael Johns - 1 month ago 10
Javascript Question

Simple JavaScript Regex replace is not working on Token with Square Brackets?

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]

Answer

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));