Neta Meta Neta Meta - 1 year ago 54
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
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

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

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download