Languages
[Edit]
EN

TypeScript - split string by space character

0 points
Created by:
Welsh
902

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 and B in the text 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' ]
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join