javascript - Escape $ in regex replacement string -



javascript - Escape $ in regex replacement string -

i want turn string dkfj-dkfj-sflj dkfj-woop$dkfj-sflj.

here's 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 result is: dkfj-woop$2-sflj. because "$" in front end of "$2" capture group, messes capture group.

assuming want construction of regex , capture grouping string remain same, what's right way escape "$" works?

that isn't how escape $ replace. backslash escaping works @ parser level, functions replace cannot give special meaning new escape sequences \$ because don't see \$. string "\$" equivalent string "$", both produce same string. if wanted pass backslash , dollar sign function, it's backslash requires escaping: "\\$".

regardless, replace expects escape $ $$. need "$1$woop[$$$2]$3"; $$ literal $, , $2 capture group.

read specifying string parameter in replace docs.

javascript regex

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -