Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 //

like image 337
Neta Meta Avatar asked May 29 '13 01:05

Neta Meta


People also ask

What is the use of G in regex?

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.

What is G at the end of regex?

The regex matches the _ character. The g means Global, and causes the replace call to replace all matches, not just the first one.

What is replace (/ g in JavaScript?

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.

How do you replace every instance of a character in a string?

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.


2 Answers

I have found split/join satisfactory enough for most of my cases. A real-life example:

myText.split("\n").join('<br>');
like image 164
pilat Avatar answered Oct 09 '22 18:10

pilat


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);
like image 45
TheBestGuest Avatar answered Oct 09 '22 16:10

TheBestGuest