How about counting the number of open parenthesis? If the count is zero, you're safe to split.
var
input = '(a),(b),(c(d,e)),(f(g(h,i,j)))',
i = 0,
lim = input.length,
output = [],
count = 0,
stack = [],
c;
for (; i < lim; i += 1) {
c = input.charAt(i);
switch (c) {
case '(':
count += 1;
break;
case ')':
count -= 1;
break;
case ',':
if (count === 0) {
output.push(stack.join(''));
stack = [];
continue;
}
break;
}
stack.push(c);
}
if (stack.length > 0) {
output.push(stack.join(''));
}
console.log(output); // ["(a)", "(b)", "(c(d,e))", "(f(g(h,i,j)))"]
http://jsbin.com/otofog/1/
or alternatively (if you're not targeting IE < 9):
function mySplit(input) {
var count = 0, output = [], stack;
stack = input.split('').reduce(function (stack, c) {
switch (c) {
case '(': count += 1; break;
case ')': count -= 1; break;
case ',':
if (count === 0) {
output.push(stack.join(''));
return [];
}
}
stack.push(c);
return stack;
}, []);
if (stack.length > 0) {
output.push(stack.join(''));
}
return output;
}
console.log( mySplit('(a),(b),(c(d,e)),(f(g(h,i,j)))') );
http://jsbin.com/ohasuc/1/
.split("),(")it should work. Were you using .split(",") before?),and then concatenating back the)on all elements but the last?(a),(b),(c(d,e),(f,g))(so even.split("),(")will fail)? Or do you think @WarrenR 's comment is helpful enough to be an answer?