views:

188

answers:

4

As the title states, I need to relace all occurrences of the $ sign in a string variable with an underscore.

I have tried:

str.replace(new RegExp('$', 'g'), '_');

But this doesn't work for me and nothing gets replaced.

+1  A: 

........

str.replace(new RegExp('\\$', 'g'), '_');

Becaue $ is special char in js, you need to escape it.

Sarfraz
The second is wrong on two counts, it will replace `\$`, not `$` and it will only replace 1 occurrence, not multiple.
Andy E
@Andy: Yes, realized it and removed it soon :) Thanks
Sarfraz
+11  A: 

The $ in RegExp is a special character, so you need to escape it with backslash.

new_str = str.replace(new RegExp('\\$', 'g'), '_');

however, in JS you can use the simpler syntax

new_str = str.replace(/\$/g, '_');
KennyTM
+1, go for the literal, don't bother with the constructor unless you need to use variables in regular expressions.
Andy E
+3  A: 

You don’t need to use RegExp. You can use the literal syntax:

str.replace(/\$/g, '_')

You just need to escape the $ character as it’s a special character in regular expressions that marks the end of the string.


Edit    Oh, you can also use split and join to solve this:

str.split("$").join("_")
Gumbo
A: 

You don't need regular expressions just to replace one symbol:

 newStr = oldStr.replace('$', '_')
stereofrog
The title stated "all" occurrences.
KennyTM
https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
stereofrog