Categories
JavaScript Answers

How to remove double spaces inside a string with JavaScript?

Spread the love

Sometimes, we want to remove double spaces inside a string with JavaScript.

In this article, we’ll look at how to remove double spaces inside a string with JavaScript.

How to remove double spaces inside a string with JavaScript?

To remove double spaces inside a string with JavaScript, we can call the string’s replace method with a regex.

For instance, we write:

const s = "hello         world"
const newS = s.replace(/\s{2,}/g, ' ');
console.log(newS)

We call replace with a regex that matches 2 or more spaces in s and replace them with single spaces.

Therefore, newS is 'hello world'.

Conclusion

To remove double spaces inside a string with JavaScript, we can call the string’s replace method 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 *