EN
JavaScript - split string with more than 1 space between words
0 points
In this article, we would like to show you how to split a string with more than 1 space between words in JavaScript.
Quick solution:
xxxxxxxxxx
1
let text = 'A B C';
2
3
// split by one or more whitespace characters regex - \s+
4
let split1 = text.split(/\s+/);
5
6
// split string from 2 to 8 spaces
7
let split2 = text.split(/\s{2,8}/);
8
9
console.log(split1); // A,B,C
10
console.log(split2); // A B,C
In this example, we use \s+
regex to split the text
string by one or more whitespace characters between words.
Runnable example:
xxxxxxxxxx
1
let text = 'A B C';
2
3
// split by one or more whitespace characters regex - \s+
4
let split = text.split(/\s+/);
5
6
console.log(split); // A,B,C
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:
xxxxxxxxxx
1
let text = 'A B C';
2
3
// split string from 2 to 8 spaces
4
let split = text.split(/\s{2,8}/);
5
6
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.