Why does string.split with a regular expression that contains a capturing group return an array that ends with an empty string?

前端 未结 4 1843
说谎
说谎 2020-12-10 10:46

I\'d like to split an input string on the first colon that still has characters after it on the same line.

For this, I am using the regular expression /:(.+)/<

4条回答
  •  一生所求
    2020-12-10 11:17

    From the ECMAScript 2015 spec (String.prototype.split):

    If separator is a regular expression that contains capturing parentheses, then each time separator is matched the results (including any undefined results) of the capturing parentheses are spliced into the output array. For example,

      "Aboldandcoded".split(/<(\/)?([^<>]+)>/)
    

    evaluates to the array:

      ["A", undefined, "B", "bold", "/", "B", "and", undefined,
      "CODE", "coded", "/", "CODE", ""]
    

    Like in your example example, the output array here contains a trailing empty string, which is the portion of the input string past "coded" that isn't captured by the separator pattern (which captures "/" and "CODE").

    Not obvious, but makes sense as otherwise the separator captures would end up in the end of the split array where they actually would not separate anything.

提交回复
热议问题