Neta Meta Neta Meta - 5 days ago 5
Javascript Question

replace all without a regex where can i use the G

So i have the following:

var token = '[token]';
var tokenValue = 'elephant';
var string = 'i have a beautiful [token] and i sold my [token]';
string = string.replace(token, tokenValue);


The above will only replace the first
[token]
and leave the second on alone.

If I were to use regex I could use it like

string = string.replace(/[token]/g, tokenValue);


And this would replace all my
[tokens]


However I don't know how to do this without the use of
//

Answer

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