4

I want to replace the statement below:

"(?)".replace("?", "$'")

My expectation is:

($')

But the result actually is:

())

How can I correct my code?

vietean
  • 2,975
  • 9
  • 40
  • 65

2 Answers2

6

You need to use $$' if you want replace to $' because $' is a special replacement pattern that

Inserts the portion of the string that follows the matched substring.

All the available patterns are:

$$ Inserts a "$".

$&: Inserts the matched substring.

$`: Inserts the portion of the string that precedes the matched substring.

$': Inserts the portion of the string that follows the matched substring.

$n or $nn: Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Community
  • 1
  • 1
Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • If the replacement is a variable, I don't know if it exist any $ character. Should I replace all $ by $$ for every the replacement? – vietean Aug 13 '15 at 04:57
  • If you want `$` character instead of using it as the special patten, you need to use `$$` – Bryan Chen Aug 13 '15 at 04:59
  • 1
    @vietean Not sure whether I understood your question correctly, but whenever you want to replace something _by_ a dollar sign, you use `$$` every time as the second argument of the `replace` function. Only a `$$` safely creates a single `$` this way. – Sebastian Simon Aug 13 '15 at 04:59
4

You need

"(?)".replace("?", "$$'")

$' is a special replacement pattern (nserts the portion of the string that precedes the matched substring.) and needs to be escaped using $.


How to Do This Without an Escape Sequence

If you don't want to replace all your $ in your replacement string, you could also do something like

"(?)".replace("?", function() { return "$'" })

i.e. using a function (that returns the replacement string - no escaping needed) as the 2nd parameter.

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter

The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.)

potatopeelings
  • 40,709
  • 7
  • 95
  • 119