Languages
[Edit]
EN

TypeScript - split string with more than 1 space between words

0 points
Created by:
Richard-Bevan
413

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.

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