Remove all Commas from a String in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 12, 2021

banner

Photo from Unsplash

Remove all Commas from a String #

To remove all commas from a string:

  1. Call the replaceAll() method, passing it a comma as the first parameter and an empty string as the second.
  2. The replaceAll method returns a new string with all matches replaced by the provided replacement.
index.js
const str = '1,23,45.67'; const withoutCommas = str.replaceAll(',', ''); console.log(withoutCommas); // 👉️ '12345.67'

The first parameter we passed to the String.replaceAll method is the string we want to match, and the second parameter is the replacement for each match.

The replaceAll method does not change the contents of the original string, it returns a new string with all matches replaced. Strings are immutable in JavaScript.

We could pass a regular expression as the first parameter to the replaceAll method, but we don't have to.

For our purposes, a basic string containing a comma will suffice.

Alternatively, you can use the replace() method.

To remove all commas from a string, call the replace() method, passing it a regular expression to match all commas as the first parameter and an empty string as the second parameter. The replace method will return a new string with all of the commas removed.

index.js
const str = '1,23,45.67'; const withoutCommas = str.replace(/,/g, ''); console.log(withoutCommas); // 👉️ '12345.67'

The first parameter we passed to the String.replace method is a regular expression that matches all the commas in the string.

The forward slashes / / mark the beginning and end of the regular expression.

We used the g (global) flag at the end of the regex because we want to match all commas, and not just the first occurrence.

The second parameter is the replacement for each match. For our purposes, we replace each comma with an empty string.

The replace() method does not change the contents of the original string, it returns a new string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.