var str='true && (true || false) && true';
if (str) {
console . log('true');
} else {
console . log('false');
}
Check above dynamic string as a condition true or false.
var str='true && (true || false) && true';
if (str) {
console . log('true');
} else {
console . log('false');
}
Check above dynamic string as a condition true or false.
You could make use of eval
function. Generally speaking eval
evaluates JavaScript code represented as a string. For further info, please have a look here.
However, you should pay attention of the following remark, that you will in the link mentioned above:
eval()
is a dangerous function, which executes the code it's passed with the privileges of the caller. If you runeval()
with a string that could > be affected by a malicious party, you may end up running malicious code on the > user's machine with the permissions of your webpage / extension.
var str='true && (true || false) && true';
if(eval(str)){
console.log('true');
}
else{
console.log('false');
}
You may use a small parser:
function evaluate(str){
//remove all whitespace
str = str.replace(/\s/g,"");
//Parse stuff in brackets first:
const first = str.indexOf("("), last = str.lastIndexOf(")");
if(first != -1 && last != -1)
str = str.substr(0, first) + evaluate(str.substr(first + 1, last)) + str.substr(last + 1);
//split into or parts
return str.split("||")
//parse the or parts
.map(sub =>
//Evaluate the &&
sub.split("&&")
.every(el => el === "true")
//evaluate the or parts
).some(e => e);
}
So you can do:
if(evaluate("true && false || false")) alert("works!");