Remove Comma from String in JavaScript

In this post, we will see how to remove comma from String in Javascript.

There are multiple ways to do it. Let’s go through them.

Using replace()

To remove comma from String in Javascript:

  • Use replace() method with regular expression /\,/g as first parameter and empty string as second parameter.

Output:

The replace() method returns a new string with matches of pattern replaced by a replacement string.
It takes 2 parameters.

  1. Regular expression which we want to match in String.
  2. Replacement String – String with which we want to replace matched string.

Let’s go through regular expression /\,/g used in above replace method.

  • The forward slashes mark start and end of regular expression
  • We have used \ before , to escape it as , has special meaning in regular expression.
  • g denotes global replacement here. It is flag at end of regex which depicts that we want to remove all the commas not only first one.

replace() returns a new String, it does not change contents of original String.

Using replaceAll()

To remove comma from string in Javascript:

  • Use replaceAll() method with , as first parameter and empty string as second parameter. replaceAll() method returns new String with all matches replaced by given replacement.

The replaceAll() method returns a new string with matches of passed string replaced by a replacement string.
It takes 2 parameters.

  1. substring which we want to match in String.
  2. Replacement String – String with which we want to replace matched string.

Output:

replaceAll() method is not supported in Internet Explorer versions 6-11. Use replace method in case you are using them.

Using split() and join() method

To remove comma from String in Javascript:

  • Split the string by comma using split() method.
  • Join the String with empty String using empty space

This method is useful, when you want to avoid regular expressions in replace() method.

Output:

.
We used split() method to split the String on each occurrence of , into array.

Then joined the array elements with empty String using join() method.

That’s all about how to remove comma from string in Javascript.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *