Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. I tried something, but it doesn't seem to work(sorry, I'm a newbie in javascript):

function checkBrackets(str){
	var newOrder = [];
	var bracket1 = "(";
	var bracket2 = ")";
	for(var bracket1 in str){
		
			newOrder.push("1");
	}

	for(bracket2 in str){
		
			newOrder.pop();
	}

	if(newOrder.length == 0){
		console.log("Right!" + newOrder);
	} else{
		console.log("Wrong!" + newOrder);
	}
}

checkBrackets('( ( a + b ) / 5 – d )');

I tried to loop through the string with a for-in loop and whenever it hits a "(" to add "1" to the array. And when it hits a ")" to remove one "1" from the array. At the end if the array is empty, i could conclude, that the brackets were put correctly and if not, they weren't.

like image 885
Sharen_charshaf Avatar asked Sep 20 '25 01:09

Sharen_charshaf


1 Answers

You can do it this way :

// str is the string to parse
function checkBrackets(str){
    // depth of the parenthesis
    // ex : ( 1 ( 2 ) ( 2 ( 3 ) ) )
    var depth = 0;
    // for each char in the string : 2 cases
    for(var i in str){   
        if(str[i] == '('){
            // if the char is an opening parenthesis then we increase the depth
            depth ++;
        } else if(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 parenthesis
        if (depth < 0) return false;
    }
    // If the depth is not null then a closing parenthesis is missing
    if(depth > 0) return false;
    // OK !
    return true;
}
console.log(checkBrackets('( ( a + b ) / 5 – d )')); // true
console.log(checkBrackets('( ( ) a + b ) / 5 – d )')); // false
console.log(checkBrackets('( ) ) ( ( a + b ) / 5 – d )')); // false
like image 94
nobe4 Avatar answered Sep 21 '25 21:09

nobe4