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', '', '']