13

I want to replace a string by another. I found when the replaceValue contains "$", the replace will fail. So I am trying to escape "$" by "$$" first. The code is looks like this:

var str = ..., reg = ...;
function replaceString(replaceValue) {
  str.replace(reg, replaceValue.replace(/\$/g, '$$$$'));
}

But I think it is ugly since I need to write 4 dollar signs.

Is there any other charactors that I need to escape? And is there any better way to do this?

3 Answers 3

27

There is a way to call replace that allows us not to worry about escaping anything.

var str = ..., reg = ...;
function replaceString(replaceValue) {
  return str.replace(reg, function () { return replaceValue });
}
1
  • Specifically, the point is to wrap the replacement string in a function; that way no escaping is done to it.
    – O'Rooney
    Oct 7, 2021 at 3:49
10

Your method to escape the replacement string is correct.

According to section 15.5.4.11 String.prototype.replace of ECMAScript specification edition 5.1, all special replacement sequences begins with $ ($&, $`, $', $n, $nn) and $$ specify a single $ in the replacement.

Therefore, it is sufficient to escape all $ with double $$ like what you are doing right now if the replacement text is meant to be treated literally.

There is no other concise way to do the replacement as far as I can see.

0

Unfortunately, nothing you can do about it.
It's just how JavaScript works with regular expressions.

Here's a good article with the list of all replacement patterns you should be aware of: http://es5.github.io/#x15.5.4.11

4
  • The article doesn't say anything about avoiding them. Rather, they are the syntax of the replacement string.
    – nhahtdh
    Jan 23, 2015 at 3:42
  • Correct. But see the OP's question: Is there any other charactors that I need to escape?. The article provides the patterns he should know about.
    – Oleg Dubas
    Jan 23, 2015 at 3:46
  • I think you should change the wording to: "... list of all replacement patterns, which your method has done a good job at escaping them"
    – nhahtdh
    Jan 23, 2015 at 3:48
  • @nhahtdh, edited it my way. Thank you for your input!
    – Oleg Dubas
    Jan 23, 2015 at 3:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.