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.
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')
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.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
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, '_');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With