Replace all without a regex where can I use the G
string = string.replace(new RegExp("\\[token\\]","g"), tokenValue);
Caution with the accepted answer, the replaceWith string can contain the inToReplace string, in which case there will be an infinite loop...
Here a better version:
function replaceSubstring(inSource, inToReplace, inReplaceWith)
{
var outString = [];
var repLen = inToReplace.length;
while (true)
{
var idx = inSource.indexOf(inToReplace);
if (idx == -1)
{
outString.push(inSource);
break;
}
outString.push(inSource.substring(0, idx))
outString.push(inReplaceWith);
inSource = inSource.substring(idx + repLen);
}
return outString.join("");
}
Why not replace the token every time it appears with a do while loop?
var index = 0;
do {
string = string.replace(token, tokenValue);
} while((index = string.indexOf(token, index + 1)) > -1);
I have found split/join satisfactory enough for most of my cases. A real-life example:
myText.split("\n").join('<br>');