JavaScript split String with white space

后端 未结 7 866
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 02:40

    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)

提交回复
热议问题