Skip to content

Instantly share code, notes, and snippets.

@eugeneglova
Last active August 29, 2015 14:10
Show Gist options
  • Save eugeneglova/e3b03d4ee9d0c5ac5abe to your computer and use it in GitHub Desktop.
Save eugeneglova/e3b03d4ee9d0c5ac5abe to your computer and use it in GitHub Desktop.
Check for correct brackets in string
function check(s) {
var i = 0, l;
s = s.replace(/[^\{\}\(\)\[\]]/g, "");
l = s.length;
if ( ! l) return true;
if (l % 2 !== 0) return false;
while (s.length && i < l) {
s = s.replace(/\{\}|\(\)|\[\]/g, "");
i++;
}
return !s.length;
}
console.assert(check("a( b)") === true);
console.assert(check("[{}]") === true);
console.assert(check("[(]") === false);
console.assert(check("}{") === false);
console.assert(check("z([{}-()]{a})") === true);
console.assert(check("") === true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment