EN
JavaScript - split string by space character
0 points
In this article, we would like to show you how to split string by space character in JavaScript.
Quick solution:
xxxxxxxxxx
1
let text = 'A B C';
2
3
// simple split by space character
4
let split1 = text.split(' ');
5
6
// split by whitespace regex - \s
7
let split2 = text.split(/\s/);
8
9
// split by one or more whitespace characters regex - \s+
10
let split3 = text.split(/\s+/);
11
12
console.log(split1); // A,B,C
13
console.log(split2); // A,B,C
14
console.log(split3); // A,B,C
In this example, we use split()
method to split the text
string by a single space character.
xxxxxxxxxx
1
let text = 'A B C';
2
3
// simple split by space character
4
let split = text.split(' ');
5
6
console.log(split); // A,B,C
In this example, we split the text
string using split()
method with \s
regex that matches a single whitespace character.
xxxxxxxxxx
1
let text = 'A B C';
2
3
// split by whitespace regex - \s
4
let split = text.split(/\s/);
5
6
console.log(split); // A,,B,C
Note:
Notice that there are two space characters between
A
andB
in thetext
string.
In this example, we split the text
string using split()
method with \s+
regex that matches multiple whitespace characters.
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