Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a "raw" string search and replace in JavaScript, no REGEX [duplicate]

How do I perform a proper string search and replace in JavaScript with absolutely no REGEX involved?

I know the docs say that if the first argument to String.prototype.replace() is a string, rather than a regex, then it will do a literal replace. Practice shows that is NOT entirely true:

"I am a string".replace('am', 'are')
--> "I are a string"

OK

"I am a string".replace('am', 'ar$e')
--> "I ar$e a string"

Still OK

"I am a string".replace('am', 'ar$$e')
--> "I ar$e a string"

NOT OK!

Where's the second dollar sign? Is it looking for something like $1 to replace with a match from the REGEX... that was never used?

I'm very confused and frustrated, any ideas?

like image 761
Tony Bogdanov Avatar asked Oct 12 '16 18:10

Tony Bogdanov


1 Answers

If you use the replace callback rather than a string literal, the automatic regex substitution will not be performed:

"I am a string".replace('am', () => 'ar$$e')
like image 158
Rob M. Avatar answered Nov 03 '22 01:11

Rob M.