- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Validating a string with numbers present in it in JavaScript
- Validating a power JavaScript
- Validating a password using JavaScript
- Validating a file size in JavaScript while uploading
- Validating push pop sequence in JavaScript
- Validating string with reference to array of words using JavaScript
- Validating a square in a 2-D plane in JavaScript
- Validating a boggle word using JavaScript
- Validating alternating vowels and consonants in JavaScript
- Balance a string after removing extra brackets in C++
- Validating email and password - JavaScript
- Finding score of brackets in JavaScript
- Binary tree to string with brackets in C++
- Find digits between brackets in JavaScript RegExp?
- Finding the balance of brackets in JavaScript

Advertisements