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?
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')
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