How to do a raw string search and replace it with JavaScript, without REGEX

How to do the correct string search and replace it with JavaScript without REGEX?

I know that the docs say that if the first argument of String.prototype.replace() is a string, not a regular expression, then it will perform a literal replacement. Practice shows that this is NOT quite true:

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

Ok

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

Still ok

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

NOT OK!

Where is the second dollar sign? Is he looking for something like $1 to replace with a REGEX ... match that has never been used?

I am very confused and upset, any ideas?

+6
source share
1 answer

If you use replace callback rather than a string literal, automatic regex replacement will fail:

 "I am a string".replace('am', () => 'ar$$e') 
+4
source

All Articles