Borislav Hadzhiev
Tue Oct 12 2021·2 min read
Photo by Larm Rmah
To remove all hyphens from a string:
replaceAll()
method, passing it a hyphen as the first parameter
and an empty string as the second - replaceAll('-', '')
.replaceAll
method returns a new string with all matches replaced by the
provided replacement.const str = '1-2-3'; const hyphensRemoved = str.replaceAll('-', ''); console.log(hyphensRemoved); // 👉️ 123
We passed the following parameters to the String.replaceAll method:
-
The replaceAll
method does not change the original string, it returns a new
string with all matches replaced. Strings are immutable in JavaScript.
replaceAll
method is not supported in Internet Explorer. If you have to support the browser, use the replace
method instead.To remove all hyphens from a string:
replace()
method, passing it a regular expression that matches all
hyphens as the first parameter and an empty string as the second.replace
method will return a new string containing no hyphens.const str = '1-2-3'; const hyphensRemoved = str.replace(/-/g, ''); console.log(hyphensRemoved); // 👉️ 123
We passed the following parameters to the String.replace method:
We use the g
(global) flag in the regular expression because we want to match
all hyphens and not just the first occurrence of a hyphen.
replaceAll
method is a bit more elegant and easier to read, however if you have to support Internet Explorer, the replace
method gets the job done.