Can anyone explain to me why JavaScript outputs a single $
when using $$
as the replace value?
"hi".replace("hi", "$$bye$$");
"hi".replace("hi", "\$\$bye\$\$");
//both output -> $bye$
//but I expected $$bye$$
Can anyone explain to me why JavaScript outputs a single $
when using $$
as the replace value?
"hi".replace("hi", "$$bye$$");
"hi".replace("hi", "\$\$bye\$\$");
//both output -> $bye$
//but I expected $$bye$$
The $
acts as a metacharacter in the replacement strings for that function. The string $$
is used to indicate that you just want a $
. Otherwise, $
followed by a digit refers to the contents of a capturing group from the regular expression. As an example:
alert("aaabbb".replace(/(a+)(b+)/, "$2$1")); // bbbaaa
The string "\$\$bye\$\$" is exactly the same as the string "$$bye$$". Because $
is not a metacharacter in the string grammar, the backslash preceding it will be ignored.
You can double-up on the backslashes to have them survive the string constant parse, but the .replace()
function will pay no particular attention do them, and you'll get \$\$
in the result.