Validating brackets in a string in JavaScript


We are required to write a JavaScript function that takes in a string that might contain some opening and closing brackets. The function should whether for all the opening brackets there exists a closing bracket or not. If the brackets are rightly matched, the function should return true, false otherwise.

For example −

f('(hello (world))') = true
f('(hello (world)') = false

Example

Following is the code −

const str1 = '(hello (world))';
const str2 = '(hello (world)';
const validateBrackets = (str = '') => {
   const strArr = str.split('');
   let counter = 0;
   for (let i = 0, len = strArr.length; i < len; i++) {
      if (strArr[i] === "(") {
         counter++;
      }else if (strArr[i] === ")") {
         counter--;
      };
      if (counter < 0) {
         return false;
      };
   };
   if (counter === 0) {
      return true;
   };
   return false;
};
console.log(validateBrackets(str1));
console.log(validateBrackets(str2));

Output

Following is the output on console −

true
false

Updated on: 11-Dec-2020

822 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements