3
var text="$$$ $$ $"; 
var dummy="hello world"; 
dummy.replace("world", text);

expected output:

hello $$$ $$ $

actual output:

hello $$ $ $

i don't understand why this is happening. kindly help. it doesn't seem to happen with other symbols though.

thanks

Learner
  • 315
  • 1
  • 5
  • 15
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. – thefourtheye Mar 25 '15 at 11:17

2 Answers2

2

It's because $ has a special meaning in regular expressions, which replace uses.

See this question for more details: link

Community
  • 1
  • 1
doldt
  • 4,466
  • 3
  • 21
  • 36
2

The short answer is "because that's how String.replace works".

The docs at Mozilla Development Network are helpful here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter

The replacement string can include the following special replacement patterns:

  • $$ Inserts a "$".
  • $& Inserts the matched substring.

And so forth.. (there's more replacement rules, but I'm not going to quote the whole MDN page)

So, if we change your sample to:

var text="$$ ($&) $"; 
var dummy="hello world"; 
dummy.replace("world", text);

We get as a result:

"hello $ (world) $"

In short $& (and other sequences like $1 and $'), mean special things, and the way you escape a plain $ is by preceding it with another $.

Tim
  • 6,406
  • 22
  • 34