开发者

How can I replace all occurrences of a dollar ($) with an underscore (_) in javascript?

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

开发者_如何学PythonI have tried:

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

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


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, '_');


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("_")


........

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

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


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

 newStr = oldStr.replace('$', '_')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜