bumpkin
bumpkin

Reputation: 3469

Escape $ in regex replacement string

I want to turn the string dkfj-dkfj-sflj into dkfj-woop$dkfj-sflj.

Here's what I've tried:

var my_string = "dkfj-dkfj-sflj";
var regex = new RegExp("(\\w+)-(\\w+)-(\\w+)", "g");
console.log(my_string.replace(regex, "$1$woop[\$$2]$3");

And my result is: dkfj-woop$2-sflj. Because the "$" is in front of the "$2" capture group, it messes up that capture group.

Assuming I want the structure of my regex and capture group string to stay the same, what's the right way to escape that "$" so it works?

Upvotes: 0

Views: 74

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

Use $$ in the replacement part to print a literal $ symbol and you don't need to have a character class in the replacement part if your pattern was enclosed within forward slashes.

> var my_string = "dkfj-dkfj-sflj";
undefined
> my_string.replace(/(\w+)-\w+-(\w+)/, "$1-woop$$$1-$2")
'dkfj-woop$dkfj-sflj'

Upvotes: 1

user229044
user229044

Reputation: 239301

That isn't how you escape a $ for replace. Backslash escaping works at the parser level, functions like replace cannot give special meaning to new escape sequences like \$ because they don't even see the \$. The string "\$" is exactly equivalent to the string "$", both produce the same string. If you wanted to pass a backslash and a dollar sign to a function, it's the backslash itself that requires escaping: "\\$".

Regardless, replace expects you to escape a $ with $$. You need "$1$woop[$$$2]$3"; a $$ for the literal $, and $2 for he capture group.

Read Specifying a string as a parameter in the replace docs.

Upvotes: 3

Related Questions