6

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?

Tony Bogdanov
  • 7,436
  • 10
  • 49
  • 80
  • The second dollar sign gets eaten away because of [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter). – Ali Gajani Oct 12 '16 at 18:30
  • The question remains is, why are these quirks even active since I'm not using regex in the first place? Seems just stupid to me. – Tony Bogdanov Oct 12 '16 at 18:32
  • @TonyBogdanov because it is defined that way in [15.5.4.11 String.prototype.replace (searchValue, replaceValue)](http://www.ecma-international.org/ecma-262/5.1/#sec-15.5.4.11). If you want to know why the api was designed that way, then you would need to ask the persons that where involved with this decision. But even if you don't use a regex it could be useful to e.g. insert some char into a given string based on a search value: `"test 1234".replace("12", "$&-");` – t.niese Oct 12 '16 at 18:41

1 Answers1

6

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')
Rob M.
  • 35,491
  • 6
  • 51
  • 50