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:
const text: string = 'A B C';
// simple split by space character
const split1: string[] = text.split(' ');
// split by whitespace regex - \s
const split2: string[] = text.split(/\s/);
// split by one or more whitespace characters regex - \s+
const split3: string[] = text.split(/\s+/);
console.log(split1); // [ 'A', 'B', 'C' ]
console.log(split2); // [ 'A', 'B', 'C' ]
console.log(split3); // [ 'A', 'B', 'C' ]
1. Simple split by single space char
In this example, we use split()
method to split the text
string by a single space character.
const text: string = 'A B C';
// simple split by space character
const split: string[] = text.split(' ');
console.log(split); // [ 'A', 'B', 'C' ]
Output:
[ 'A', 'B', 'C' ]
2. Split by whitespace regex - \s
In this example, we split the text
string using split()
method with \s
regex that matches a single whitespace character.
const text: string = 'A B C';
// split by whitespace regex - \s
const split: string[] = text.split(/\s/);
console.log(split); // [ 'A', 'B', 'C' ]
Output:
[ 'A', 'B', 'C' ]
Note:
Notice that there are two space characters between
A
andB
in thetext
string.
3. Split by one or more whitespace regex - \s+
In this example, we split the text
string using split()
method with \s+
regex that matches multiple whitespace characters.
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' ]