How to split string while ignoring portion in parentheses?

前端 未结 5 1474
南方客
南方客 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:32

    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 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.

提交回复
热议问题