Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

I have tried:

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

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

like image 534
Ryan Tomlinson Avatar asked Mar 12 '10 17:03

Ryan Tomlinson


People also ask

How do you replace all occurrences of a character in a string in JavaScript?

To make the method replace() replace all occurrences of the pattern you have to enable the global flag on the regular expression: Append g after at the end of regular expression literal: /search/g. Or when using a regular expression constructor, add 'g' to the second argument: new RegExp('search', 'g')

How do you replace every instance of a character in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.

What is $1 in replace JavaScript?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.


1 Answers

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, '_'); 
like image 165
kennytm Avatar answered Sep 28 '22 11:09

kennytm