Split string on the first white space occurrence

后端 未结 13 2004
孤街浪徒
孤街浪徒 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:07

    Most of the answers above search by space, not whitespace. @georg's answer is good. I have a slightly different version.

    s.trim().split(/\s(.*)/).splice(0,2)
    

    I'm not sure how to tell which is most efficient as the regexp in mine is a lot simpler, but it has the extra splace.

    (@georg's for reference is s.split(/(?<=^\S+)\s/))

    The question doesn't specify how to handle no whitespace or all whitespace, leading or trailing whitespace or an empty string, and our results differ subtly in those cases.

    I'm writing this for a parser that needs to consume the next word, so I prefer my definition, though @georg's may be better for other use cases.

    input.        mine              @georg
    'aaa bbb'     ['aaa','bbb']     ['aaa','bbb']
    'aaa bbb ccc' ['aaa','bbb ccc'] ['aaa','bbb ccc']
    'aaa '        [ 'aaa' ]         [ 'aaa', '' ]
    ' '           [ '' ]            [ ' ' ]
    ''            ['']              ['']
    ' aaa'        ['aaa']           [' aaa']
    
    0 讨论(0)
提交回复
热议问题