[javascript] JavaScript - Replace all commas in a string

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?

This question is related to javascript string replace substitution

The answer is


Just for fun:

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

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

Use the global(g) flag

Simple DEMO


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to replace

How do I find and replace all occurrences (in all files) in Visual Studio Code? How to find and replace with regex in excel How to replace text in a column of a Pandas dataframe? How to replace negative numbers in Pandas Data Frame by zero Replacing few values in a pandas dataframe column with another value How to replace multiple patterns at once with sed? Using tr to replace newline with space replace special characters in a string python Replace None with NaN in pandas dataframe Batch script to find and replace a string in text file within a minute for files up to 12 MB

Examples related to substitution

How can I combine multiple nested Substitute functions in Excel? bash: Bad Substitution Remove all newlines from inside a string JavaScript - Replace all commas in a string Substitute multiple whitespace with single whitespace in Python How to use a variable in the replacement side of the Perl substitution operator?