function isFine(str) {
return /[(){}\[\]]/.test( str ) &&
( str.match( /\(/g ) || '' ).length == ( str.match( /\)/g ) || '' ).length &&
( str.match( /\[/g ) || '' ).length == ( str.match( /]/g ) || '' ).length &&
( str.match( /{/g ) || '' ).length == ( str.match( /}/g ) || '' ).length;
}
Test
isFine('(this is fine and does not need attention)'); // true
isFine('This is also [fine]'); // true
isFine('This is bad( and needs to be edited'); // false
isFine('This [is (also) bad'); // false
isFine('as is this} bad'); // false
isFine('this string has no brackets but must also be considered'); // false
Note though, that this doesn't check bracket order, i.e. a)b(c
would be deemed fine.
For the record, here is a function that checks for missing brackets and checks that each type is correctly balanced. It doesn't allow a)b(c
, but it does allow (a[bc)d]
as each type is checked individually.
function checkBrackets( str ) {
var lb, rb, li, ri,
i = 0,
brkts = [ '(', ')', '{', '}', '[', ']' ];
while ( lb = brkts[ i++ ], rb = brkts[ i++ ] ) {
li = ri = 0;
while ( li = str.indexOf( lb, li ) + 1 ) {
if ( ( ri = str.indexOf( rb, ri ) + 1 ) < li ) {
return false;
}
}
if ( str.indexOf( rb, ri ) + 1 ) {
return false;
}
}
return true;
}
Finally, further to Christophe's post, here is what seems the best solution to checking for missing brackets and checking that all are correctly balanced and nested:
function checkBrackets( str ) {
var s;
str = str.replace( /[^{}[\]()]/g, '' );
while ( s != str ) {
s = str;
str = str.replace( /{}|\[]|\(\)/g, '' )
}
return !str;
};
checkBrackets( 'ab)cd(efg' ); // false
checkBrackets( '((a)[{{b}}]c)' ); // true
checkBrackets( 'ab[cd]efg' ); // true
checkBrackets( 'a(b[c)d]e' ); // false