Javascript String Replace Weirdness -- $$$$ Gets Collapsed To $$ -- What's The Reason Behind This Result?
At work, I was encountering a problem where users of our application were receiving messages featuring an invalid unicode character (0xffff), which according to the standard, shoul
Solution 1:
That's because $
in the replace string has special meaning (group expansion). Have a look at this example:
alert("foo".replace(/(.*)/, "a$1b"));
That's why $$
is interpreted as $
, for the case where you would need to actually replace something by $1
(literally, without group expansion):
alert("foo".replace(/(.*)/, "a$$1b"));
Solution 2:
The $
sign is a special character in the replacement argument to denote sub-matches from parentheses in the regex pattern ($1
, $2
, etc.). So to get a $
you have to "escape" it by typing $$
. Which is what you did twice.
Solution 3:
The $ in a replace string is used to signal the use of the match groups $1, $2 etc, si to put a $ into the replace string you need to use two of them.
Post a Comment for "Javascript String Replace Weirdness -- $$$$ Gets Collapsed To $$ -- What's The Reason Behind This Result?"