Languages
[Edit]
EN

JavaScript - split string by space character

0 points
Created by:
Gigadude
791

In this article, we would like to show you how to split string by space character in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

let text = 'A B C';

// simple split by space character
let split1 = text.split(' ');

// split by whitespace regex - \s
let split2 = text.split(/\s/);

// split by one or more whitespace characters regex - \s+
let split3 = 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.

// ONLINE-RUNNER:browser;

let text = 'A B C';

// simple split by space character
let split = text.split(' ');

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

// ONLINE-RUNNER:browser;

let text = 'A  B C';

// split by whitespace regex - \s
let split = text.split(/\s/);

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

// 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

References

Alternative titles

  1. JavaScript - split String with white space
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.

JavaScript - String (popular problems)

JavaScript - split string by space character
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