JSFiddle - React, Tailwind, and code Playground
JavaScript
var test = function(str) {
var chars = str.split(''),
stack = [],
open = ['{', '(', '['],
close = ['}', ')', ']'],
closeIndex,
openIndex;
for (var i = 0, len = chars.length; i < len; i++) {
openIndex = open.indexOf(chars[i]);
if (openIndex !== -1) {
stack.push(openIndex);
continue;
}
closeIndex = close.indexOf(chars[i]);
if (closeIndex !== -1) {
openIndex = stack.pop();
if (closeIndex !== openIndex) {
return false;
}
}
}
if (stack.length !== 0) {
return false;
}
return true;
}
console.log(test('text with([brackets])')); // true
console.log(test('text with ([wrong brackets)]')); // false
console.log(test('text with [wrong brackets')); // false