2

I am trying to replace a string with multiple $ symbol in JavaScript using replace function. But all of the $ symbols are not getting written.

For eg:

var a = "xyz";
a = a.replace("xyz", "$$$");
console.log(a)

Output:

$$
Salman A
  • 262,204
  • 82
  • 430
  • 521
coder
  • 23
  • 4
  • 4
    The `$` character is special in replacement strings. You have to use two `$` characters for every one you actually want. – Pointy Jun 26 '18 at 14:33

2 Answers2

3

The $ symbol has special meaning when used inside String.replace. You can escape it by doubling it:

var a = "xyz";
a = a.replace("xyz", "$$$$$$");
console.log(a)
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • but even for "$$$$$" (5 dollar symbols) it prints "$$$" (3 dollar symbols) – coder Jun 26 '18 at 15:32
  • Yes. To be more precise, the $ symbol needs to be followed by certain characters e.g. digits or $ symbol to have an effect (see doc). The 5th $ symbol in your example is not substituted and displayed as-is. – Salman A Jun 26 '18 at 17:31
0

$ is a special character. so you have to use additional $ for each of them

var a = "xyz";
a = a.replace("xyz", "$$$$$$");
console.log(a)
alynurly
  • 1,669
  • 1
  • 15
  • 15