JavaScript - Replace all commas in a string

JavascriptStringReplaceSubstitution

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

The third parameter of String.prototype.replace() function was never defined as a standard, so most browsers simply do not implement it.

The best way is to use regular expression with g (global) flag.

var myStr = 'this,is,a,test'; var newStr = myStr.replace(/,/g, '-');

console.log( newStr );  // "this-is-a-test"

Still have issues?

It is important to note, that regular expressions use special characters that need to be escaped. As an 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).

var myStr = 'this.is.a.test'; var newStr = myStr.replace(/./g, '-');

console.log( newStr );  // "this-is-a-test"

If you need to pass a variable as a replacement string, instead of using regex literal you may create RegExp object and pass a string as the first argument of the constructor. The normal string escape rules (preceding special characters with \ when included in a string) will be necessary.

var myStr = 'this.is.a.test'; var reStr = '\.'; var newStr = myStr.replace(new RegExp(reStr, 'g'), '-');

console.log( newStr );  // "this-is-a-test"

Solution 2 - Javascript

Just for fun:

var mystring = "this,is,a,test"  
var newchar = '|'
mystring = mystring.split(',').join(newchar);

Solution 3 - Javascript

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikeView Question on Stackoverflow
Solution 1 - JavascriptVisioNView Answer on Stackoverflow
Solution 2 - JavascriptRobGView Answer on Stackoverflow
Solution 3 - Javascriptgdoron is supporting MonicaView Answer on Stackoverflow