TypeScript - split string
This article focuses on different ways how to split string to array. TypeScript provides String.prototype.split
method that can be used to do it.
1. Splitting string by text
Each string can be splitted in TypeScript 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.
const text: string = 'This is some text...';
const array: string[] = text.split(' '); // space character separator used
console.log(array);
Output:
['This', 'is', 'some', 'text...']
1.2. Split string by some text example
This section shows how to split string by some other string.
const text: string = 'This is some text...';
const array: string[] = text.split('is'); // this character sequence separates string
console.log(array);
Output:
['Th', ' ', ' some text...']
1.3. Split string to array of characters example
In this apprach empty string is used to split main string into array of characters.
const text: string = 'This is some text...';
const array: string[] = text.split(''); // empty separator used
console.log(array);
Output:
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', 's', 'o', 'm', 'e', ' ', 't', 'e', 'x', 't', '.', '.', '.']
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.
const text: string = 'This is some text...';
const array: string[] = text.split(' ', 2); // maximum result array size will be 2
console.log(array);
Output:
['This', 'is']
2. Split string with regex (regular expression)
Each string can be splitted in TypeScript 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.
const text: string = 'This is some text...';
const array: string[] = text.split(/\b/); // begin or end of word separates string
console.log(array);
Output:
['This', ' ', 'is', ' ', 'some', ' ', 'text', '...']
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.
const text: string = 'This is some text...';
const array: string[] = text.split(/\b/, 2); // maximum result array size will be 2
console.log(array);
Output:
['This', ' ']