- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements