Split string on the first white space occurrence

后端 未结 13 2007
孤街浪徒
孤街浪徒 2020-11-28 20:07

I didn\'t get an optimized regex that split me a String basing into the first white space occurrence:

var str=\"72 tocirah sneab\";

I need

13条回答
  •  离开以前
    2020-11-28 21:06

    Just split the string into an array and glue the parts you need together. This approach is very flexible, it works in many situations and it is easy to reason about. Plus you only need one function call.

    arr = str.split(' ');             // ["72", "tocirah", "sneab"]
    strA = arr[0];                    // "72"
    strB = arr[1] + ' ' + arr[2];     // "tocirah sneab"
    

    Alternatively, if you want to cherry-pick what you need directly from the string you could do something like this:

    strA = str.split(' ')[0];                    // "72";
    strB = str.slice(strA.length + 1);           // "tocirah sneab"
    

    Or like this:

    strA = str.split(' ')[0];                    // "72";
    strB = str.split(' ').splice(1).join(' ');   // "tocirah sneab"
    

    However I suggest the first example.

    Working demo: jsbin

提交回复
热议问题