Remove all Commas from a String in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 12 20212 min read

banner

Photo by Matthew Henry

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 pass 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.

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 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
// Supported in IE 6-11 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.

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

The second parameter is the replacement for each match, in our case we replace all commas with an empty string.

The replace method does not change the contents of the original string, it returns a new string with the matches replaced.

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