public
Created

JavaScript that uses a Regex to split a string, ensuring balanced parenthesis and balanced quotes.

  • Download Gist
Example.js
JavaScript
1 2 3 4 5 6 7 8 9
var input = "a, b, (c, d), (e, (f, g), h), 'i, j, (k, l), m', 'n, \"o, 'p', q\", r'";
var result = SplitBalanced(input, ",");
// Results:
["a",
" b",
" (c, d)",
" (e, (f, g), h)",
" 'i, j, (k, l), m'",
" 'n \"o, 'p', q\", r'"];
SplitBalanced.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
function SplitBalanced(input, split, open, close, toggle, escape) {
// Build the pattern from params with defaults:
var pattern = "([\\s\\S]*?)(e)?(?:(o)|(c)|(t)|(sp)|$)"
.replace("sp", split)
.replace("o", open || "[\\(\\{\\[]")
.replace("c", close || "[\\)\\}\\]]")
.replace("t", toggle || "['\"]")
.replace("e", escape || "[\\\\]");
var r = new RegExp(pattern, "gi");
var stack = [];
var buffer = [];
var results = [];
input.replace(r, function($0,$1,$e,$o,$c,$t,$s,i){
if ($e) { // Escape
buffer.push($1, $s || $o || $c || $t);
return;
}
else if ($o) // Open
stack.push($o);
else if ($c) // Close
stack.pop();
else if ($t) { // Toggle
if (stack[stack.length-1] !== $t)
stack.push($t);
else
stack.pop();
}
else { // Split (if no stack) or EOF
if ($s ? !stack.length : !$1) {
buffer.push($1);
results.push(buffer.join(""));
buffer = [];
return;
}
}
buffer.push($0);
});
return results;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.