EN
TypeScript - split string with more than 1 space between words
0
points
In this article, we would like to show you how to split a string with more than 1 space between words in TypeScript.
Quick solution:
const text: string = 'A B C';
// split by one or more whitespace characters regex - \s+
const split1: string[] = text.split(/\s+/);
// split string from 2 to 8 spaces
const split2: string[] = text.split(/\s{2,8}/);
console.log(split1); // [ 'A', 'B', 'C' ]
console.log(split2); // [ 'A B', 'C' ]
1. Split by one or more whitespace characters regex - \s+
In this example, we use \s+
regex to split the text
string by one or more whitespace characters between words.
Runnable example:
const text: string = 'A B C';
// split by one or more whitespace characters regex - \s+
const split: string[] = text.split(/\s+/);
console.log(split); // [ 'A', 'B', 'C' ]
Output:
[ 'A', 'B', 'C' ]
2. Split string from 2 to 8 spaces using \s{2,8}
regex
In this example, we use \s{2,8}
regex to split the text
string that contains from 2 to 8 whitespace characters between words.
Runnable example:
const text: string = 'A B C';
// split string from 2 to 8 spaces
const split: string[] = text.split(/\s{2,8}/);
console.log(split); // [ 'A B', 'C' ]
Output:
[ 'A B', 'C' ]
Note:
Notice that
A B
is a single element because there is only one space character between the letters.