dangreen
dangreen

Reputation: 339

Escaping $$ in `replace` function

I met next trouble on my way:

"abc".replace("ab","$$ $$")
>>> "$ $c"
"abc".replace("ab","\$\$ \$\$")
>>> "$ $c"

How i can escape $ symbol ?

Upvotes: 1

Views: 85

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

In the replacement string, $$ = $. So if you really want $$, use $$$$.

"abc".replace("ab","$$$$ $$$$") // "$$ $$c"

No backslashes are required. Details in the specification.


Side note: Only the first occurrence of ab will be replaced, because your first argument is a string. E.g.:

"abc abc abc".replace("ab","$$$$ $$$$") // "$$ $$c abc abc"

If you wanted all occurrences replaced, you'd have to make your first argument a regular expression with the g (global) flag:

"abc abc abc".replace(/ab/g,"$$$$ $$$$") // "$$ $$c $$ $$c $$ $$c"

Upvotes: 3

Related Questions