Split string on the first white space occurrence

后端 未结 13 2069
孤街浪徒
孤街浪徒 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 20:45

    Javascript doesn't support lookbehinds, so split is not possible. match works:

    str.match(/^(\S+)\s(.*)/).slice(1)
    

    Another trick:

    str.replace(/\s+/, '\x01').split('\x01')
    

    how about:

    [str.replace(/\s.*/, ''), str.replace(/\S+\s/, '')]
    

    and why not

    reverse = function (s) { return s.split('').reverse().join('') }
    reverse(str).split(/\s(?=\S+$)/).reverse().map(reverse)
    

    or maybe

    re = /^\S+\s|.*/g;
    [].concat.call(re.exec(str), re.exec(str))
    

    2019 update: as of ES2018, lookbehinds are supported:

    str = "72 tocirah sneab"
    s = str.split(/(?<=^\S+)\s/)
    console.log(s)

提交回复
热议问题