function balance(str, a, b) {
  var aarr = str.split(a);
  var alen = aarr.join('').length;
  var blen = str.split(b).join('').length;

  if (alen !== blen) {
    str = aarr.join('\\' + a);
    return str.split(b).join('\\' + b);
  }

  return str;
}
Escape imbalanced braces/bracket. This is a very
basic, naive implementation that only does enough
to serve the purpose.