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 parsefunctioncheckBrackets(str){
    // depth of the parenthesis// ex : ( 1 ( 2 ) ( 2 ( 3 ) ) )var depth = 0;
    // for each char in the string : 2 casesfor(var i in str){   
        if(str[i] == '('){
            // if the char is an opening parenthesis then we increase the depth
            depth ++;
        } elseif(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 parenthesisif (depth < 0) returnfalse;
    }
    // If the depth is not null then a closing parenthesis is missingif(depth > 0) returnfalse;
    // OK !returntrue;
}
console.log(checkBrackets('( ( a + b ) / 5 – d )')); // trueconsole.log(checkBrackets('( ( ) a + b ) / 5 – d )')); // falseconsole.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:

functioncheckBrackets(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: 000.5em0;
  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.

functionIsValid(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)) {
          returnfalse;
        }
        break;
    }
  }

  return leftBraces.length === 0; 
}

functionMatch(brackets) {
  switch (brackets) {
    case'()': case'{}': case'[]':
      returntrue;
    default:
      returnfalse;
  }
}

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

console.log(IsValid('c[d]')) // trueconsole.log(IsValid('a{b[c]d}e')) // trueconsole.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"