I want to replace the statement below:
"(?)".replace("?", "$'")
My expectation is:
($')
But the result actually is:
())
How can I correct my code?
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
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.)
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