Vishal Kumar Verma Vishal Kumar Verma - 4 months ago 34
Javascript Question

Javascript: Split a string by comma, except inside parentheses

Given string in the form:

'"abc",ab(),c(d(),e()),f(g(),zyx),h(123)'


How can I split it to get the below array format:

abc
ab()
c(d(),e())
f(g(),zyx)
h(123)


I have tried normal javascript split, however it doesn't work as desired. Trying Regular Expression but not yet successful.

Answer

You can keep track of the parentheses, and add those expressions when the left and right parens equalize.

For example-

function splitNoParen(s){
    var left= 0, right= 0, A= [], 
    M= s.match(/([^()]+)|([()])/g), L= M.length, next, str= '';
    for(var i= 0; i<L; i++){
        next= M[i];
        if(next=== '(')++left;
        else if(next=== ')')++right;
        if(left!== 0){
            str+= next;
            if(left=== right){
                A[A.length-1]+=str;
                left= right= 0;
                str= '';
            }
        }
        else A=A.concat(next.match(/([^,]+)/g));
    }
    return A;
}

var s1= '"abc",ab(),c(d(),e()),f(g(),zyx),h(123)';
splitNoParen(s1).join('\n');

/*  returned value: (String)
"abc"
ab()
c(d(),e())
f(g(),zyx)
h(123)
*/
Comments