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 //
RegExp. prototype. global has the value true if the g flag was used; otherwise, false . The g flag indicates that the regular expression should be tested against all possible matches in a string.
The regex matches the _ character. The g means Global, and causes the replace call to replace all matches, not just the first one.
The "g" that you are talking about at the end of your regular expression is called a "modifier". The "g" represents the "global modifier". This means that your replace will replace all copies of the matched string with the replacement string you provide.
To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.
I have found split/join satisfactory enough for most of my cases. A real-life example:
myText.split("\n").join('<br>');
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With