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

后端 未结 4 1943
傲寒
傲寒 2021-01-03 19:29

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(\'$         


        
4条回答
  •  时光说笑
    2021-01-03 20:05

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

提交回复
热议问题