Why is the '/g' required when using string replace in JavaScript?
e.g. var myString = myString.replace(/%0D%0A/g,"<br />");
Definition and Usage. The "g" modifier specifies a global match. A global match finds all matches (compared to only the first).
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.
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.
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.
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.
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