I have a string with multiple commas, and the string replace method will only change the first one:
var mystring = "this,is,a,test"
mystring.replace(",","newchar", -1)
Result: "thisnewcharis,a,test"
The documentation indicates that the default replaces all, and that “-1” also indicates to replace all, but it is unsuccessful. Any thoughts?
The third parameter of the
String.prototype.replace()function was never defined as a standard, so most browsers simply do not implement it. It was eventually removed and replaced withString.prototype.replaceAll()(see below).Modern solution (2022)
Use
String.prototype.replaceAll(). It is now supported in all browsers and NodeJS.The old way is to use a regular expression with
g(global) flagHave issues with regular expressions?
It is important to note, that regular expressions use special characters that need to be escaped. For example, if you need to escape a dot (
.) character, you should use/\./literal, as in the regex syntax a dot matches any single character (except line terminators).If you need to pass a variable as a replacement string, instead of using regex literal you may create a
RegExpobject and pass a string as its first argument. The usual escape rules (preceding special characters with\when included in a string) will be necessary.