javascript split string by space, but ignore space in quotes (notice not to split by the colon too)

后端 未结 3 1208
再見小時候
再見小時候 2020-12-03 02:45

I need help splitting a string in javascript by space (\" \"), ignoring space inside quotes expression.

I have this string:

var str = \'Time:\"Last 7         


        
3条回答
  •  感动是毒
    2020-12-03 03:32

    s = 'Time:"Last 7 Days" Time:"Last 30 Days"'
    s.match(/(?:[^\s"]+|"[^"]*")+/g) 
    
    // -> ['Time:"Last 7 Days"', 'Time:"Last 30 Days"']
    

    Explained:

    (?:         # non-capturing group
      [^\s"]+   # anything that's not a space or a double-quote
      |         #   or…
      "         # opening double-quote
        [^"]*   # …followed by zero or more chacacters that are not a double-quote
      "         # …closing double-quote
    )+          # each match is one or more of the things described in the group
    

    Turns out, to fix your original expression, you just need to add a + on the group:

    str.match(/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g)
    #                         ^ here.
    

提交回复
热议问题