Borislav Hadzhiev
Tue Oct 12 2021·2 min read
Photo by Matthew Henry
To remove all commas from a string:
replaceAll()
method, passing it a comma as the first parameter and
an empty string as the second.replaceAll
method returns a new string with all matches replaced by the
provided replacement.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.
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.
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.
// 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 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.
replace
method does not change the contents of the original string, it returns a new string with the matches replaced.