Skip to content Skip to sidebar Skip to footer

JS Function For Validation Of The Brackets In A String

guys! I want to ask you how can a make a function, that checks if the brackets in a string are put correctly. For example '(a + b).4,2 - )c + 5)' and I have to check the brackets.

Solution 1:

You can do it this way :

// str is the string to parse
function checkBrackets(str){
    // depth of the parenthesis
    // ex : ( 1 ( 2 ) ( 2 ( 3 ) ) )
    var depth = 0;
    // for each char in the string : 2 cases
    for(var i in str){   
        if(str[i] == '('){
            // if the char is an opening parenthesis then we increase the depth
            depth ++;
        } else if(str[i] == ')') {
            // if the char is an closing parenthesis then we decrease the depth
            depth --;
        }  
        //  if the depth is negative we have a closing parenthesis 
        //  before any matching opening parenthesis
        if (depth < 0) return false;
    }
    // If the depth is not null then a closing parenthesis is missing
    if(depth > 0) return false;
    // OK !
    return true;
}
console.log(checkBrackets('( ( a + b ) / 5 – d )')); // true
console.log(checkBrackets('( ( ) a + b ) / 5 – d )')); // false
console.log(checkBrackets('( ) ) ( ( a + b ) / 5 – d )')); // false

Solution 2:

While you've accepted an answer already, I felt it was a little complex, so I thought I'd expand on the naive solution I presented in the comments to the question:

function checkBrackets(str) {
  // using a regular expression to find the number '(' characters in the string,
  // escaping with a '\' because '(' is a special character within a regular
  // expression; if no matches are found, and the result of 'match()' is falsey,
  // we instead assign an empty array (in order that calling 'length', later, on
  // a potentially-null object, won't create an error):
  var opens = str.match(/\(/g) || [],
    closes = str.match(/\)/g) || [];

  // if there are equal numbers of '(' and ')' characters, we return true,
  // otherwise false:
  return opens.length === closes.length;
}

// unnecessary, this is just a means of iterating over the <li> elements, to work on
// a range of inputs for the function:
Array.prototype.forEach.call(document.getElementsByTagName('li'), function(li) {
  // li is the <li> element/node itself, li.textContent is the text contained within
  // that <li>, using the classList API to add a 'valid' class (if brackets are balanced)
  // or an 'invalid' class (if the brackets are not balanced):
  li.classList.add(checkBrackets(li.textContent) ? 'valid' : 'invalid');
});
ul {
  margin: 0;
  padding: 0;
}
li {
  list-style-type: none;
  margin: 0 0 0.5em 0;
  padding: 0.5em;
  width: 100%;
  box-sizing: border-box;
}
.valid {
  border: 1px solid #0f0;
}
.invalid {
  border: 1px solid #f00;
}
<ul>
  <li>( ( a + b ) / 5 - d )</li>
  <li>( a + b ) / 5 - d</li>
  <li>( a + b ) / ( 5 - d )</li>
  <li>( a + b ) / 5 - d )</li>
  <li>a + b ) / 5 - d</li>
  <li>( a + b / 5 - d</li>
</ul>

References:


Solution 3:

Here's how I would do it to handle not just parentheses but other characters as well. If it's more than just parentheses you need to validate, then you need to implement a stack/array. You can also use the length of the stack instead of declaring a balance/depth/count variable.

function IsValid(text) {
  const leftBraces = [];

  for (let i = 0; i < text.length; i++) {
    const char = text[i];

    switch (Brace(char)) {
      case 'L':
        leftBraces.push(char);
        break;
      case 'R':
        if (!Match(leftBraces.pop() + char)) {
          return false;
        }
        break;
    }
  }

  return leftBraces.length === 0; 
}

function Match(brackets) {
  switch (brackets) {
    case '()': case '{}': case '[]':
      return true;
    default:
      return false;
  }
}

function Brace(c) {
  switch (c) {
    case ')': case '}': case ']':
      return 'R';
    case '(': case '{': case '[':
      return 'L';
    default:
      return ''; 
  }
}

console.log(IsValid('c[d]')) // true
console.log(IsValid('a{b[c]d}e')) // true
console.log(IsValid('a{b(c]d}e')) // false - ] doesn’t match (
console.log(IsValid('a[b{c}d]e}')) // false - nothing matches final }
console.log(IsValid('a{b(c)')) // false - no matching }

Post a Comment for "JS Function For Validation Of The Brackets In A String"