如何在javascript中用下划线(_)替换所有出现的美元($)? [英] How can I replace all occurrences of a dollar ($) with an underscore (_) in javascript?
本文介绍了如何在javascript中用下划线(_)替换所有出现的美元($)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正如标题所述,我需要在一个带有下划线的字符串变量中重新发生所有$符号。
As the title states, I need to relace all occurrences of the $ sign in a string variable with an underscore.
我试过:
str.replace(new RegExp('$', 'g'), '_');
但这对我不起作用,没有任何东西可以替换。
But this doesn't work for me and nothing gets replaced.
推荐答案
RegExp中的 $
是一个特殊字符,所以你需要用反斜杠转义它。
The $
in RegExp is a special character, so you need to escape it with backslash.
new_str = str.replace(new RegExp('\\$', 'g'), '_');
然而,在JS中你可以使用更简单的语法
however, in JS you can use the simpler syntax
new_str = str.replace(/\$/g, '_');
这篇关于如何在javascript中用下划线(_)替换所有出现的美元($)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文