JavaScript - how to split string?
This article focuses on different ways how to split string to array. JavaScript provides String.prototype.split
method that can be used to do it.
1. Splitting string by text
Each string can be splitted in JavaScript with other string.
1.1. Split string by space example
In this example string with single space is used to spltit 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 apprach empty string is used to split main string into 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 splitted in JavaScript with regular expresion.
2.1. Split string by white character symbol example
In this example white character symbol is used to spltit text to 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 white character symbol is used to spltit text to 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
Example how to use splitter is described in this article.