95

I would like to split a String but I would like to keep white space like:

var str = "my car is red";
var stringArray [];
stringArray [0] = "my";
stringArray [1] = " ";
stringArray [2] = "car";
stringArray [3] = " ";
stringArray [4] = "is";
stringArray [5] = " ";
stringArray [6] = "red";

How I can proceed to do that?

Thanks !

asked Oct 17, 2014 at 13:02

8 Answers 8

139

Using regex:

var str = "my car is red";
var stringArray = str.split(/(\s+)/);
console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"] 

\s matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.

answered Oct 17, 2014 at 13:06
Sign up to request clarification or add additional context in comments.

5 Comments

Huh, this actually works. Can you explain what the filter is doing? At first glance it appears to be invalid since the filter callback is supposed to return true or false.
You're a lifesaver. Nothing else would work for my particular case!
You probably want: var stringArray = str.split(/\s+/); to no have the whitespace in your array.
@run_the_race Could you explain why what he did preserve the spaces?
@MinhNghĩa "If separator is a regular expression that contains capturing parentheses (), matched results are included in the array."
67

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
 string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
 stringArray.push(string[i]);
 if(i != string.length-1){
 stringArray.push(" ");
 }
}
starball
59.9k53 gold badges322 silver badges1k bronze badges
answered Oct 17, 2014 at 13:04

2 Comments

This doesn't work well at all with double spaces. "text to split" (2 spaces between "text to") => ["text", " ", "", " ", "to", " ", "split"]
@Rhumborl No it does't and you could build that in, but it does what it says on the tin. Natural text does not contain double spaces. If you want it though, you could add if(string[i] === "") continue; at the beginning of the loop to ignore any empty values.
59

For split string by space like in Python lang, can be used:

var w = "hello my brothers ;";
w.split(/(\s+)/).filter( function(e) { return e.trim().length > 0; } );

output:

["hello", "my", "brothers", ";"]

or similar:

w.split(/(\s+)/).filter( e => e.trim().length > 0)

(output some)

answered Sep 21, 2016 at 22:36

2 Comments

w.split(/(\s+)/).filter( e => e.length > 1)
The previous comment is wrong. 'a boy'.split(/(\s+)/).filter( e => e.length > 1) gives ["boy"]
8

You can just split on the word boundary using \b. See MDN

"\b: Matches a zero-width word boundary, such as between a letter and a space."

You should also make sure it is followed by whitespace \s. so that strings like "My car isn't red" still work:

var stringArray = str.split(/\b(\s)/);

The initial \b is required to take multiple spaces into account, e.g. my car is red

EDIT: Added grouping

answered Oct 17, 2014 at 13:07

2 Comments

I wouldn't suggest this. \b doesn't only match between a letter and a space: it also matches the boundary between letters and punctuation, for example. "Bob's e-mail is [email protected]" becomes ["Bob", "'", "s", " ", "e", "-", "mail", " ", "is", " ", "a", "@", "b", ".", "com"]
@Shai true, added the space check too
6

Although this is not supported by all browsers, if you use capturing parentheses inside your regular expression then the captured input is spliced into the result.

If separator is a regular expression that contains capturing parentheses, then each time separator is matched, the results (including any undefined results) of the capturing parentheses are spliced into the output array. [reference)

So:

var stringArray = str.split(/(\s+)/);
 ^ ^
//

Output:

["my", " ", "car", " ", "is", " ", "red"]

This collapses consecutive spaces in the original input, but otherwise I can't think of any pitfalls.

answered Oct 17, 2014 at 13:13

Comments

4

In case you're sure you have only one space between two words, you can use this one

str.replace(/\s+/g, ' ').split(' ')

so you replace one space by two, the split by space

answered Oct 26, 2020 at 11:32

Comments

3

You can use two white space in the split function as below

str.split(" ");

This will split the string with spaces.

answered Nov 2, 2022 at 18:22

Comments

2
str.split(' ').join('§ §').split('§');
answered Jul 11, 2016 at 20:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.