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

前端 未结 4 1841
说谎
说谎 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:28

    My regexp always generates an extra element at the end of the array returned by string.prototype.split(). So I simply truncate the array every time. Seems better than Array.filter when it's always the last element that is removed. I'm parsing CSS/SVG transforms, splitting on both left and right parentheses. Either of these works: /\(|\)/ or /[\(\)]/.
    For example:

    arr = "rotate(90  46  88) scale(1.2 1.2)".split(/\(|\)/);
    arr.length--;
    

    Or if you want to get fancy and cram it into one line:

    (arr = "rotate(90  46  88) scale(1.2 1.2)".split(/\(|\)/)).length--;
    

    The result is: ["rotate","90 46 88","scale","1.2 1.2"]

提交回复
热议问题