Split a String by Multiple Spaces in JavaScript

avatar

Borislav Hadzhiev

Thu Nov 18 20211 min read

Split a String by Multiple Spaces in JavaScript #

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str.trim().split(/\s+/). The regular expression will split the string on one or more spaces and return an array containing the substrings.

index.js
const str = ' banana kiwi mango '; const result = str.trim().split(/\s+/); console.log(result); // ๐Ÿ‘‰๏ธ ['banana', 'kiwi', 'mango']

We called the String.trim method on the string to remove any leading or trailing spaces.

index.js
console.log(' a '.trim()); // ๐Ÿ‘‰๏ธ "a"

This helps us avoid the scenario where the array that the String.split method returns contains empty elements.

index.js
const str = ' banana kiwi mango '; // โ›”๏ธ without trim // ๐Ÿ‘‡๏ธ ['', 'banana', 'kiwi', 'mango', ''] console.log(str.split(/\s+/));

The only parameter we passed to the split() method is a regular expression.

The forward slashes / / mark the beginning and end of the regular expression.

The \s special character matches any whitespace (spaces, tabs, newlines).

The plus + matches one or more of the preceding item (the spaces). In other words, the plus matches one or more spaces, treating them as a single match.

If you ever need help reading a regular expression, check this regex cheatsheet from MDN out.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee