For some reason the "".replace()
method only replaces the first occurrence and not the others. Any ideas?
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match.
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.
replace() is an inbuilt method in JavaScript which is used to replace a part of the given string with some another string or a regular expression. The original string will remain unchanged. Parameters: Here the parameter A is regular expression and B is a string which will replace the content of the given string.
You have to use the g
modifier (for global) in your replace call.
str = str.replace(/searchString/g, "replaceWith")
In your particular case it would be:
str = str.replace (/\//g, "_");
Note that you must escape the /
in the regular expression.
"Your/string".split("/").join("_")
if you don't require the power of RegExp
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