Categories
JavaScript Answers

How to split string with white space with JavaScript?

Spread the love

Sometimes, we want to split string with white space with JavaScript.

In this article, we’ll look at how to split string with white space with JavaScript.

How to split string with white space with JavaScript?

To split string with white space with JavaScript, we use the string split method.

For instance, we write

const arr = w.split(/(\s+)/).filter((e) => e.trim().length > 0);

to call split with a regex that matches whitespaces.

Then we call filter with a function that returns the strings that has length bigger than 0 after trimming the starting and ending whitespaces with trim.

/(\s+)/ matches whitespaces in string w and use them as separators.

Conclusion

To split string with white space with JavaScript, we use the string split method.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.