Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do i need to add /g when using string replace in Javascript?

Tags:

javascript

Why is the '/g' required when using string replace in JavaScript?

e.g. var myString = myString.replace(/%0D%0A/g,"<br />");

like image 396
Tesseract Avatar asked Jul 30 '09 14:07

Tesseract


People also ask

What does G do in JavaScript?

Definition and Usage. The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).

How do you use G to replace?

To perform a global search and replace, use a regular expression with the g flag, or use replaceAll() instead. If pattern is an object with a Symbol. replace method (including RegExp objects), that method is called with the target string and replacement as arguments.

How does replace method work in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

What is G in regex?

The g flag indicates that the regular expression should be tested against all possible matches in a string. A regular expression defined as both global ( g ) and sticky ( y ) will ignore the global flag and perform sticky matches.


1 Answers

It isn't required, but by default string.replace in JavaScript will only replace the first matching value it finds. Adding the /g will mean that all of the matching values are replaced.

like image 97
Eifion Avatar answered Oct 10 '22 12:10

Eifion