Borislav Hadzhiev
Tue Oct 12 2021·2 min read
Photo by Noémi Macavei-Katócz
To replace all hyphens in a string:
replaceAll()
method, passing it a hyphen as the first parameter
and the replacement string as the second.replaceAll
method returns a new string with all matches replaced by the
provided replacement.const str = 'a-b-c'; const hyphensReplaced = str.replaceAll('-', ' '); console.log(hyphensReplaced); // 👉️ a b c
We passed the following parameters to the String.replaceAll method:
In the example we replace each hyphen with a space, however you could provide
any replacement that suits your use case, e.g. a dot .
:
const str = 'a-b-c'; const hyphensReplaced = str.replaceAll('-', '.'); console.log(hyphensReplaced); // 👉️ a.b.c
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 versions 6-11. If you have to support the browser, use the replace
method instead.To replace all hyphens in a string:
replace()
method, passing it a regular expression matching all
hyphens as the first parameter and the replacement string as the second.replace
method will return a new string with all hyphens replaced with
the provided replacement.// Supported in IE 6-11 const str = 'a-b-c'; const hyphensReplaced = str.replace(/-/g, ' '); console.log(hyphensReplaced); // 👉️ a b c
We passed the following parameters to the String.replace method:
We use the g
(global) flag because we want to match all hyphens in the string
and not just the first occurrence.
replace
method does not mutate the original string, it returns a new string with one or more matches replaced.The replaceAll
method is quite nicer and easier to read, however if you have
to support Internet Explorer, the replace
method gets the job done.