Replace all Commas in a String using JavaScript

avatar

Borislav Hadzhiev

Fri Oct 29 20212 min read

banner

Photo by Kevin Laminto

Replace all Commas in a String #

Use the replaceAll() method to replace all commas in a string, e.g. str.replaceAll(',', ' '). The replaceAll method takes a substring and a replacement as parameter and returns a new string with all matches replaced by the provided replacement.

index.js
const str = 'a,long,string'; const commasReplaced = str.replaceAll(',', ' '); console.log(commasReplaced); // 👉️ a long string

We passed the following parameters to the String.replaceAll method:

  1. a substring we're looking to match in the string, in our case a comma ,
  2. the replacement for each match
In the example we replace each comma with a space, however you could provide a replacement string that matches your use case, e.g. an underscore.
index.js
const str = 'a,long,string'; const commasReplaced = str.replaceAll(',', '_'); console.log(commasReplaced); // 👉️ a_long_string

Note that the replaceAll method does not change the original string, it returns a new string with all matches replaced by the provided replacement.

The replaceAll method is not supported in Internet Explorer versions 6-11. If you need to support the browser, use the replace method instead.

Use the replace() method to replace all commas in a string, e.g. str.replace(/,/g, ' '). The method takes a regular expression and a replacement string as parameters and returns a new string with the matches replaced by the provided replacement.

index.js
const str = 'a,long,string'; const commasReplaced = str.replace(/,/g, ' ') console.log(commasReplaced) // 👉️ a long string

We passed the following parameters to the String.replace method:

  1. a regular expression matching all commas in the string
  2. a replacement for each match

We used the g (global) flag because we want to match all commas in the string and not just the first occurrence.

In the example we replaced each comma with a space, however you can provide a replacement string that suites your use case.

The replace method does not mutate the original string, it returns a new string. Strings are immutable in JavaScript.

The replaceAll method is quite a bit easier to read than replace, however if you have to support Internet Explorer, replace gets the job done.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.