Sometimes, we want to replace dash or hyphen with a space in JavaScript.
In this article, we’ll look at how to replace dash or hyphen with a space in JavaScript.
How to replace dash or hyphen with a space in JavaScript?
To replace dash or hyphen with a space in JavaScript, we call replace
with a regex.
For instance, we write
const str = "This-is-a-news-item-";
const newStr = str.replace(/-/g, " ");
to call str.replace
with /-/g
and an empty string to replace all dashes or hyphens with an empty string.
The g
flag ensures that all matches are replaced.
A new string with the replacements done is returned.
Conclusion
To replace dash or hyphen with a space in JavaScript, we call replace
with a regex.