1

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$$
jamcoupe
  • 1,422
  • 1
  • 19
  • 31
  • Also http://stackoverflow.com/questions/28102491/javascript-better-way-to-escape-dollar-signs-in-the-string-used-by-string-prot. Also https://www.google.com/search?q=string+replace+dollar+sign+javascript. –  May 30 '15 at 14:03

1 Answers1

2

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614