Categories
JavaScript Answers

How to remove whitespaces with a regular expression and JavaScript?

Spread the love

Sometimes, we want to remove whitespaces with a regular expression and JavaScript.

In this article, we’ll look at how to remove whitespaces with a regular expression and JavaScript.

How to remove whitespaces with a regular expression and JavaScript?

To remove whitespaces with a regular expression and JavaScript, we can use the string replace method.

For instance, we write:

const str = "    bob is a good      boy     "
const s = str.replace(/^\s+|\s+$|\s+(?=\s)/g, "");
console.log(s)

to call str.replace with the /^\s+|\s+$|\s+(?=\s)/g regex.

The regex matches whitespaces at the start of a string with ^\s+.

It matches whitespaces at the end of a string with \s+$.

And it matches multiple whitespaces within the string with \s+(?=\s).

The g flag returns all matches in the string.

And then we replace them all with an empty string.

Therefore, s is 'bob is a good boy'.

Conclusion

To remove whitespaces with a regular expression and JavaScript, we can use the string replace method.

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 *