JavaScript - split string
This article focuses on different ways how to split string into array. JavaScript provides String.prototype.split
method that can be used to do it.
Each string can be split in JavaScript with other strings.
In this example string with a single space is used to split text to single words.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split(' '); // space character separator used
console.log(array);
This section shows how to split string by some other string.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split('is'); // this character sequence separates string
console.log(array);
In this approach empty string is used to split the main string into an array of characters.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split(''); // empty separator used
console.log(array);
Note: this approach is strongly not recommended because of unicode characters that can be misinterpreted.
This section shows how to split string by space limiting output array size to two elements.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split(' ', 2); // maximum result array size will be 2
console.log(array);
Each string can be split in JavaScript with regular expression.
In this example, the white character symbol is used to split text into single words.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split(/\b/); // begin or end of word separates string
console.log(array);
In this example, a white character symbol is used to split text into single words limiting output array size to two elements.
xxxxxxxxxx
var text = 'This is some text...';
var array = text.split(/\b/, 2); // maximum result array size will be 2
console.log(array);
An example of how to use a splitter is described in this article.