Skip to content Skip to sidebar Skip to footer

Regex Split String By Spaces Taking Into Account Nested Brackets

I know that this has been asked/answered several times but unfortunately none of the solutions I've tried so far works in my case. I need to split something like this: contrast(200

Solution 1:

Here is my solution:

functionsplitBySpaces(string){
    var openBrackets = 0, ret = [], i = 0;
    while (i < string.length){
        if (string.charAt(i) == '(')
            openBrackets++;
        elseif (string.charAt(i) == ')')
            openBrackets--;elseif (string.charAt(i) == " " && openBrackets == 0){
            ret.push(string.substr(0, i));
            string = string.substr(i + 1);
            i = -1;
        }
        i++;
    }

    if (string != "") ret.push(string);
    return ret;
}

Solution 2:

You may split a string on spaces/tabs that are outside of nested parentheses using the code below:

functionsplitOnWhitespaceOutsideBalancedParens() {
  var item = '', result = [], stack = 0, whitespace = /\s/;
  for (var i=0; i < text.length; i++) {
    if ( text[i].match(whitespace) && stack == 0 ) {
        result.push(item);
        item = '';
        continue;
    } elseif ( text[i] == '(' ) {
        stack++;
    } elseif ( text[i] == ')' ) {
        stack--;
    }
    item += text[i];
  }
  result.push(item);
  return result;
}

var text = "contrast(200%) drop-shadow(rgba(0, 0, 0, 0.5) 0px 0px 10px)";
console.log(splitOnWhitespaceOutsideBalancedParens(text));

Post a Comment for "Regex Split String By Spaces Taking Into Account Nested Brackets"