JavaScript split String with white space

后端 未结 7 823
隐瞒了意图╮
隐瞒了意图╮ 2020-12-08 01:56

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\";
string         


        
相关标签:
7条回答
  • 2020-12-08 02:42

    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.

    0 讨论(0)
提交回复
热议问题