How to Split a String by Space in JavaScript
Splitting a string into an array of words or tokens is one of the most common string manipulation tasks. Whether you're parsing user input, processing a sentence, or breaking down a list of keywords, the String.prototype.split() method is the essential tool for the job.
This guide will demonstrate the best modern techniques for splitting a string by spaces. You will learn how to handle single spaces, multiple consecutive spaces, and how to trim whitespace from the resulting substrings.
The Core Method: String.prototype.split()
The split() method divides a string into an ordered list of substrings, puts these substrings into an array, and returns the array. The division is done by searching for a pattern, which can be a simple string or a more powerful regular expression.
'your string'.split(separator)
How to Split by a Single Space
This is the most basic use case. If you are certain your string has words separated by single, consistent spaces, you can use a simple space character as the separator.
For example, you have a simple, clean string to split into words.
// Problem: Split this sentence into an array of words.
const sentence = 'Hello world from tutorialreference.com';
Solution:
const sentence = 'Hello world from tutorialreference.com';
const words = sentence.split(' ');
console.log(words);
// Output: ['Hello', 'world', 'from', 'tutorialreference.com']
Limitation: This simple method fails if there are multiple spaces between words, or leading/trailing spaces, as it will create empty strings in your array.
const messySentence = ' leading and trailing spaces ';
const words = messySentence.split(' ');
console.log(words);
// Output: ['', '', 'leading', '', '', 'and', 'trailing', 'spaces', '', '']
How to Split by Multiple Spaces or Other Whitespace (Recommended)
For real-world data, you can't rely on clean, single-space separators. The robust and recommended solution is to use a regular expression that matches one or more whitespace characters.
For example, you have a messy string with inconsistent spacing and you need a clean array of words.
// Problem: Split this string into words, ignoring the extra spaces.
const messySentence = ' leading and trailing spaces ';
The solution uses the regular expression /\s+/ as the separator.
const messySentence = ' leading and trailing spaces ';
// First, trim any leading/trailing spaces, then split.
const words = messySentence.trim().split(/\s+/);
console.log(words);
// Output: ['leading', 'and', 'trailing', 'spaces']
How it works
trim():String.prototype.trim()is an essential first step. It removes whitespace from both the beginning and end of the string. This prevents thesplit()method from creating empty strings at the start or end of the array./\s+/: This is the regular expression.\s: Matches any whitespace character (including space, tab, and newline).+: Is a quantifier that matches the preceding token (\s) one or more times. This tellssplit()to treat any sequence of one or more spaces as a single delimiter.
How to Split by a Delimiter and Trimming Whitespace
Another common scenario is splitting by a specific character (like a comma or hyphen) where the substrings might have inconsistent padding with spaces.
For example, you have a list separated by commas, but the spacing is messy.
// Problem: Split by comma and clean up the extra spaces.
const data = 'apple , banana, cherry , date';
Solution: You can split by the delimiter and then use map() with trim() to clean each resulting element.
const data = 'apple , banana, cherry , date';
const fruits = data.split(',').map(item => item.trim());
console.log(fruits);
// Output: ['apple', 'banana', 'cherry', 'date']
A More Advanced Regex Solution
You can also solve this with a more advanced regular expression in the split() method itself.
const data = 'apple , banana, cherry , date';
// The regex /\s*,\s*/ matches a comma surrounded by zero or more spaces.
const fruits = data.split(/\s*,\s*/);
console.log(fruits);
// Output: ['apple', 'banana', 'cherry', 'date']
This regex is very useful for parsing loosely formatted data.
Conclusion
Splitting strings by spaces is a fundamental task with a clear best practice for modern JavaScript.
- For simple strings with single-space delimiters,
string.split(' ')is sufficient. - For real-world strings with inconsistent or multiple spaces, the robust and recommended best practice is to first trim the string, then split using a regular expression:
string.trim().split(/\s+/). - When splitting by a different delimiter (like a comma) and you need to clean up surrounding whitespace, chain the
.map(item => item.trim())method after splitting.