Search code examples
javascriptarrayssplit

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

  • 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(" ");
        }
    }