Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not replace "?" by "$'", it so weird [duplicate]

Tags:

javascript

I want to replace the statement below:

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

My expectation is:

($')

But the result actually is:

())

How can I correct my code?

like image 202
vietean Avatar asked Dec 25 '22 15:12

vietean


2 Answers

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

like image 132
Bryan Chen Avatar answered Jan 13 '23 05:01

Bryan Chen


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.)

like image 26
potatopeelings Avatar answered Jan 13 '23 06:01

potatopeelings