Sultan Shakir Sultan Shakir - 1 year ago 84
Javascript Question

How to split string while ignoring portion in parentheses?

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 though even if they contain commas.

For example:

"bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"

Should become:

["bibendum", "morbi", "non", "quam (nec, dui, luctus)", "rutrum", "nulla"]

But when I use a basic
, it returns:

["bibendum", " morbi", " non", " quam (nec", " dui", " luctus)", " rutrum", " nulla"]

I need it to return:

["bibendum", " morbi", " non", " quam (nec, dui, luctus)", " rutrum", " nulla"]

Your help is appreciated.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download