skip to content

Escaping $ in replace strings in Javascript

To have a $ in your replace strings in Javascript regular expressions, it needs to be escaped with another $

I.e., $$, not \$. In other words, the escape character for the RegExp “language” is $, even within Javascript, not the standard slash \n

"I <feeling> that".replace(/<(.+?)>/g, "$$1");
//won't work - will produce ""I $1 that""

"I <feeling> that".replace(/<(.+?)>/g, "$$$1");
//works - "I $feeling that"