EN
TypeScript - split string by space character
0 points
In this article, we would like to show you how to split string by space character in TypeScript.
Quick solution:
xxxxxxxxxx
1
const text: string = 'A B C';
2
3
// simple split by space character
4
const split1: string[] = text.split(' ');
5
6
// split by whitespace regex - \s
7
const split2: string[] = text.split(/\s/);
8
9
// split by one or more whitespace characters regex - \s+
10
const split3: string[] = text.split(/\s+/);
11
12
console.log(split1); // [ 'A', 'B', 'C' ]
13
console.log(split2); // [ 'A', 'B', 'C' ]
14
console.log(split3); // [ 'A', 'B', 'C' ]
In this example, we use split()
method to split the text
string by a single space character.
xxxxxxxxxx
1
const text: string = 'A B C';
2
3
// simple split by space character
4
const split: string[] = text.split(' ');
5
6
console.log(split); // [ 'A', 'B', 'C' ]
Output:
xxxxxxxxxx
1
[ 'A', 'B', 'C' ]
In this example, we split the text
string using split()
method with \s
regex that matches a single whitespace character.
xxxxxxxxxx
1
const text: string = 'A B C';
2
3
// split by whitespace regex - \s
4
const split: string[] = text.split(/\s/);
5
6
console.log(split); // [ 'A', 'B', 'C' ]
Output:
xxxxxxxxxx
1
[ 'A', 'B', 'C' ]
Note:
Notice that there are two space characters between
A
andB
in thetext
string.
In this example, we split the text
string using split()
method with \s+
regex that matches multiple whitespace characters.
xxxxxxxxxx
1
const text: string = 'A B C';
2
3
// split by one or more whitespace characters regex - \s+
4
const split: string[] = text.split(/\s+/);
5
6
console.log(split); // [ 'A', 'B', 'C' ]
Output:
xxxxxxxxxx
1
[ 'A', 'B', 'C' ]