
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Checking the validity of parentheses in JavaScript
We are required to write a JavaScript function that takes in a string str containing just the characters −
'(', ')', '{', '}', '[' and ']'
Our function should determine if the input string is valid.
An input string is valid if −
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
For example −
"()" is a valid parenthesis
"()[]{}" is a valid parentheses
"(]" is an invalid parenthesis
Example
The code for this will be −
const str = "()[]{}"; const isValid = (str = '') => { const map=new Map(); map.set('{','}'); map.set('(',')'); map.set('[',']'); const b=[]; for(let i=0;i<str.length;i++){ if(map.has(str.charAt(i))){ b.push(str.charAt(i)); } else{ let pop=b.pop(); if(map.get(pop)!==str.charAt(i)){ return false; } }; }; return b.length===0; }; console.log(isValid(str));
Output
And the output in the console will be −
true false
- Related Articles
- Checking validity of equations in JavaScript
- Finding the validity of a hex code in JavaScript
- JavaScript: Balancing parentheses
- Finding the longest valid parentheses JavaScript
- Removing parentheses from mathematical expressions in JavaScript
- Types of Validity
- Checking for the Gapful numbers in JavaScript
- Checking smooth sentences in JavaScript
- Checking the intensity of shuffle of an array - JavaScript
- Checking the equality of array elements (sequence dependent) in JavaScript
- Checking for special type of Arrays in JavaScript
- Checking for uniqueness of a string in JavaScript
- Checking for permutation of a palindrome in JavaScript
- Checking for squared similarly of arrays in JavaScript
- Checking for particular types of matrix in JavaScript

Advertisements