How to split string while ignoring portion in parentheses?

前端 未结 5 1483
南方客
南方客 2020-12-11 17:51

I have a string that I want to split into an array by using the commas as delimiters. I do not want the portions of the string that is between parentheses to be split thoug

5条回答
  •  忘掉有多难
    2020-12-11 18:40

    Instead of focusing on what you do not want it's often easier to express as a regular expression what you want, and to match that with a global regex:

    var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla";
    str.match(/[^,]+(?:\(+*?\))?/g) // the simple one
    str.match(/[^,\s]+(?:\s+\([^)]*\))?/g) // not matching whitespaces
    

提交回复
热议问题