Replace all Commas in a String using JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Kevin Laminto

Replace all Commas in a String #

To replace all commas in a string:

  1. Call the replaceAll() method, passing it a string containing a comma as the first parameter and the replacement string as the second.
  2. The replaceAll method 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.

To replace all commas in a string:

  1. Call the replace() method, passing it a regular expression matching all commas as the first parameter and the replacement string as the second.
  2. The replace method will return a new string with all commas 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee