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
It's because $ has a special meaning in regular expressions, which replace uses.
See this question for more details: link
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 $.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With