JavaScript split String with white space
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 !
Solution 1:
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.
Solution 2:
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(" ");
}
}
Update: Removed trailing space.