0

I would like to replace all occurences of a particular string with $$ in javascript.

However when I attempt the replace it only replaces a single character http://jsfiddle.net/PrZ9y/

text = "sfsd";
text =text.replace(/sf/gi,"\$\$");
document.getElementById("x").innerHTML=text;

This for example outputs $sd. The correct output should be $$sd

I also tried

text =text.replace(/sf/gi,"$$");
cjds
  • 8,268
  • 10
  • 49
  • 84

4 Answers4

2

Since $ is reserved for regular expression, doubling-up on $ will escaped it's intended purpose.

text = "sfsd";
text = text.replace(/sf/gi,"$$$$");
document.getElementById("x").innerHTML = text;
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Which is completely ridiculous, of course XD Backslash escapes everything else, including in regex patterns. But yup, this is correct. +1 – Niet the Dark Absol Mar 02 '14 at 18:19
  • Look at Java's `printf()`: You have to type `%` twice to actually print it. – Mr. Polywhirl Mar 02 '14 at 18:20
  • @NiettheDarkAbsol: `\$` is resolved **before** the string value is passed to `replace`. And since `\$` is an invalid escape sequence and equivalent to `$`, all the string value the function receives is `$$`. Not much it can do about it. – Felix Kling Mar 02 '14 at 18:22
1

Dollar sign has a special meaning, it means the number of captured group when used in conjuction with a number, like $1. $$ is just the literal for $, the first $ will play the role of escape character. Use $$$$ for $$.

More info: http://es5.github.io/#x15.5.4.11

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
1

$$ is reserved just like $& is reserved, so use three of them:

text=text.replace(/sf/gi,"$$$");
Cilan
  • 13,101
  • 3
  • 34
  • 51
  • Actually, only certain patterns of `$` followed by another characters are reserved. That includes `$$` or `$&`. And that's why this solution works. A single/sole `$` has no specific meaning (and is taken literally). Nice! – Felix Kling Mar 02 '14 at 18:31
  • @FelixKling Thanks, I am going to edit my answer... – Cilan Mar 02 '14 at 18:58
1

Try putting your html as:

<div id="x">sf sd</div>
<div id="wmd-input"></div>

Then, change your code to:

text = document.getElementById("x").innerHTML;
text = text.replace(/sf/gi,"$$$$");
document.getElementById("wmd-input").innerHTML = text;

jsfiddle.

As @Mr Polywhirl noted, you need to use another $ to escape the $ and get one literal $ sign.

Jerry
  • 70,495
  • 13
  • 100
  • 144