How to split string while ignoring portion in parentheses?

var regex = /,(?![^(]*\)) /;
var str = "bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla"; 

var splitString = str.split(regex);

Here you go. An explanation of the regex:

,     //Match a comma
(?!   //Negative look-ahead. We want to match a comma NOT followed by...
[^(]* //Any number of characters NOT '(', zero or more times
/)    //Followed by the ')' character
)     //Close the lookahead.

You don't need fancy regular expressions for this.

s="bibendum, morbi, non, quam (nec, dui, luctus), rutrum, nulla" 
var current='';
var parenthesis=0;
for(var i=0, l=s.length; i<l; i++){ 
  if(s[i] == '('){ 
    parenthesis++; 
    current=current+'(';
  }else if(s[i]==')' && parenthesis > 0){ 
    parenthesis--;
    current=current+')';
  }else if(s[i] ===',' && parenthesis == 0){
    console.log(current);current=''
  }else{
    current=current+s[i];
  }   
}
if(current !== ''){
  console.log(current);
}

Change console.log for an array concatenation or what ever you want.


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

Tags:

Javascript