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.
1. Splitting string by text
Each string can be split in JavaScript with other strings.
1.1. Split string by space example
In this example string with a single space is used to split text to single words.
// ONLINE-RUNNER:browser;
var text = 'This is some text...';
var array = text.split(' '); // space character separator used
console.log(array);
1.2. Split string by some text example
This section shows how to split string by some other string.
// ONLINE-RUNNER:browser;
var text = 'This is some text...';
var array = text.split('is'); // this character sequence separates string
console.log(array);
1.3. Split string to array of characters example
In this approach empty string is used to split the main string into an array of characters.
// ONLINE-RUNNER:browser;
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.
1.4. Split string by space with result size limit example
This section shows how to split string by space limiting output array size to two elements.
// ONLINE-RUNNER:browser;
var text = 'This is some text...';
var array = text.split(' ', 2); // maximum result array size will be 2
console.log(array);
2. Split string with regex (regular expression)
Each string can be split in JavaScript with regular expression.
2.1. Split string by white character symbol example
In this example, the white character symbol is used to split text into single words.
// ONLINE-RUNNER:browser;
var text = 'This is some text...';
var array = text.split(/\b/); // begin or end of word separates string
console.log(array);
2.2. Split string by white character symbol with result size limit example
In this example, a white character symbol is used to split text into single words limiting output array size to two elements.
// ONLINE-RUNNER:browser;
var text = 'This is some text...';
var array = text.split(/\b/, 2); // maximum result array size will be 2
console.log(array);
3. Split string with Symbol.split
(with splitter) example
An example of how to use a splitter is described in this article.