Split a String by Multiple Spaces in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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 String.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 or newlines).

The plus + matches the preceding item (the space) one or more times. 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.

This approach would also work if you need to split the string on multiple whitespace characters.

index.js
const str = ' banana \n \t kiwi \r\n mango '; const result = str.trim().split(/\s+/); console.log(result); // 👉️ ['banana', 'kiwi', 'mango']

The \s special characters matches any whitespace including spaces, tabs and newlines.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.