Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing a text with "$$$", gives truncated result in Javascript [duplicate]

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

like image 417
Learner Avatar asked Dec 11 '25 01:12

Learner


2 Answers

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

See this question for more details: link

like image 56
doldt Avatar answered Dec 12 '25 16:12

doldt


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 $.

like image 25
Tim Avatar answered Dec 12 '25 16:12

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!