Languages
[Edit]
EN

JavaScript - split string with more than 1 space between words

0 points
Created by:
telsa
232

In this article, we would like to show you how to split string with more than 1 space between words in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let text = 'A B    C';

// split by one or more whitespace characters regex - \s+
let split1 = text.split(/\s+/);

// split string from 2 to 8 spaces
let split2 = 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:

// ONLINE-RUNNER:browser;

let text = 'A B    C';

// split by one or more whitespace characters regex - \s+
let split = text.split(/\s+/);

console.log(split);  // 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:

// ONLINE-RUNNER:browser;

let text = 'A B    C';

// split string from 2 to 8 spaces
let split = text.split(/\s{2,8}/);

console.log(split);  // A B,C

Note:

Notice that A B is a single element because there is only one space character between the letters.

JavaScript - String (popular problems)

JavaScript - split string with more than 1 space between words
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