Borislav Hadzhiev
Thu Nov 18 2021·1 min read
Photo by Alexander Popov
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.
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.
console.log(' a '.trim()); // 👉️ "a"
This helps us avoid the scenario where the array that the String.split method returns contains empty elements.
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).
+
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.