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.
Each string can be splitted in TypeScript with other string.
In this example string with single space is used to spltit text to single words.
xxxxxxxxxx
const text: string = 'This is some text...';
const array: string[] = text.split(' '); // space character separator used
console.log(array);
Output:
xxxxxxxxxx
['This', 'is', 'some', 'text...']
This section shows how to split string by some other string.
xxxxxxxxxx
const text: string = 'This is some text...';
const array: string[] = text.split('is'); // this character sequence separates string
console.log(array);
Output:
xxxxxxxxxx
['Th', ' ', ' some text...']
In this apprach empty string is used to split main string into array of characters.
xxxxxxxxxx
const text: string = 'This is some text...';
const array: string[] = text.split(''); // empty separator used
console.log(array);
Output:
xxxxxxxxxx
['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.
This section shows how to split string by space limiting output array size to two elements.
xxxxxxxxxx
const text: string = 'This is some text...';
const array: string[] = text.split(' ', 2); // maximum result array size will be 2
console.log(array);
Output:
xxxxxxxxxx
['This', 'is']
Each string can be splitted in TypeScript with regular expresion.
In this example white character symbol is used to spltit text to single words.
xxxxxxxxxx
const text: string = 'This is some text...';
const array: string[] = text.split(/\b/); // begin or end of word separates string
console.log(array);
Output:
xxxxxxxxxx
['This', ' ', 'is', ' ', 'some', ' ', 'text', '...']
In this example white character symbol is used to spltit text to single words limiting output array size to two elements.
xxxxxxxxxx
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:
xxxxxxxxxx
['This', ' ']