1 module.exports = balanced;
2 function balanced(a, b, str) {
3 if (a instanceof RegExp) a = maybeMatch(a, str);
4 if (b instanceof RegExp) b = maybeMatch(b, str);
6 var r = range(a, b, str);
11 pre: str.slice(0, r[0]),
12 body: str.slice(r[0] + a.length, r[1]),
13 post: str.slice(r[1] + b.length)
17 function maybeMatch(reg, str) {
18 var m = str.match(reg);
19 return m ? m[0] : null;
22 balanced.range = range;
23 function range(a, b, str) {
24 var begs, beg, left, right, result;
25 var ai = str.indexOf(a);
26 var bi = str.indexOf(b, ai + 1);
29 if (ai >= 0 && bi > 0) {
33 while (i >= 0 && !result) {
36 ai = str.indexOf(a, i + 1);
37 } else if (begs.length == 1) {
38 result = [ begs.pop(), bi ];
46 bi = str.indexOf(b, i + 1);
49 i = ai < bi && ai >= 0 ? ai : bi;
53 result = [ left, right ];