How to use Regular Expression In Javascript
In this method we employ expressions to repeatedly remove valid pairs of parentheses until none remain.
- Define an expression pattern that matches pairs of parentheses.
- Enter into a loop that finds and removes pairs using replace operations with a string as replacement text.
- Repeat step 2 until no valid pairs can be found in iterations (i.e. after performing replacements without finding any matches).
- If, after completing these iterations our initial string becomes empty it means all parentheses have been successfully matched and eliminated; thus return true. Otherwise return false.
Syntax:
/pattern/modifiers;
function isValidParentheses(str) {
const regex = /(\(\)|\[\]|\{\})/g;
while (str.match(regex)) {
str = str.replace(regex, "");
}
return str.length === 0;
}
const inputString = "{[()]]}";
console.log(
`Is it a valid Paranthesis ?
${isValidParentheses(inputString)}`
);
Output
Is it a valid Paranthesis ? false
JavaScript Program to Check Valid Parentheses Using String
In this article, we will learn how we can check valid parentheses of a string, and write a program to check whether the pairs and order of β{ β, β } β, β(β, β)β, β[β, β]β in the string expression is right or not.
Example:
Input: exp = "[()][()()]()"
Output: True.
Explanation: all of the brackets are properly formed.
Input: exp = "[(])"
Output: False
Explanation: The first and fourth brackets are not balanced because there is a closing ']' before the final '('.
Table of Content
- Using the Stack
- Using Counter
- Using Regular Expression
- Using a Map for Character Matching
- Using a recursive function: