Skip to content
the poor coder

Stack-brackets to validate Brackets function in JavaScript

Poor Man
Published
Reading time
3 min read
On this page

Stack-brackets to validate Brackets function in JavaScript#

As a JavaScript developer, I have often come across the need to validate brackets in strings of code. This is especially important when we are dealing with complex expressions, as it can become difficult to keep track of opening and closing brackets.

One way to validate brackets in JavaScript is by using a stack. A stack is a data structure that allows us to keep track of elements in a Last In First Out (LIFO) order. In our case, we can push opening brackets onto the stack and pop them off when we encounter their closing counterpart. If the stack is empty at the end of the string, we know that all brackets have been properly closed.

Code Implementation#

Let's take a look at an implementation of this algorithm in JavaScript:

Text

function validateBrackets(str) {
  const stack = [];
  
  for (let i = 0; i < str.length; i++) {
    const char = str[i];
    
    if (char === '(' || char === '[' || char === '{') {
      stack.push(char);
    } else if (char === ')' && stack[stack.length - 1] === '(') {
      stack.pop();
    } else if (char === ']' && stack[stack.length - 1] === '[') {
      stack.pop();
    } else if (char === '}' && stack[stack.length - 1] === '{') {
      stack.pop();
    } else {
      return false;
    }
  }
  
  return stack.length === 0;
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

In this implementation, we loop through each character in the string and check if it is an opening or closing bracket. If it is an opening bracket, we push it onto the stack. If it is a closing bracket, we check if it matches the top of the stack. If it does, we pop the bracket off the stack. If it doesn't match or the stack is empty, we return false. Finally, if the stack is empty at the end of the loop, we return true.

Alternative Approaches#

There are several other ways to validate brackets in JavaScript. One alternative approach is to use recursion to check each pair of brackets. Another approach is to use regular expressions to sanitize the string and then count the number of opening and closing brackets to ensure they match.

Text

// Recursion approach
function validateBrackets(str) {
  if (!str) {
    return true;
  }
  
  const firstOpening = str.indexOf('(');
  const firstClosing = str.indexOf(')');
  
  if (firstClosing < firstOpening) {
    return false;
  }
  
  return validateBrackets(str.substring(firstOpening + 1, firstClosing)) &&
         validateBrackets(str.substring(firstClosing + 1));
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

// Regular expression approach
function validateBrackets(str) {
  const sanitizedStr = str.replace(/[^\(\)\[\]\{\}]/g, '');
  
  const openingBrackets = sanitizedStr.match(/\(|\[|\{/g);
  const closingBrackets = sanitizedStr.match(/\)|\]|\}/g);
  
  if (!openingBrackets || !closingBrackets || openingBrackets.length !== closingBrackets.length) {
    return false;
  }
  
  return true;
}

console.log(validateBrackets("(foo { bar (baz) [boo] })")); // true
console.log(validateBrackets("((foo { bar (baz) [boo] }))")); // false

Each approach has its own pros and cons, and the choice ultimately depends on the specific requirements of the project.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC