Categories
JavaScript Answers

How to replace dash or hyphen with a space in JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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