Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a string containing boolean values to a boolean

Tags:

javascript

If I have this ;

  var a = "(true && false) && true && false"

And if I want to evaluate this string , what are the options ?

If I say, this code will be generated in the browser but there will be absolutely no user input in it , would it be safe to use eval ?

If not, what is the most performant way of parsing it ?

EDIt :

By the way, the string is dynamic , so I can't gaurantee that it's always like above , so it could be :

  var a = "(true && false) || (true && (true && false)) && true && false"

FIY : I know I can use eval, all I'm asking is, why I shouldn't use eval, or is there any other options?

EDIT : the original problem :

 var a = function(){ return false} // all of them always return a boolean
 var b = function(){ return true}
 var c = function(){ return true}
 var d = function(){ return false}

 var conditions = "(a && b) && c && d"

I can't change the above code , I need to parse it, I need the condition to be evaluated ;

like image 557
Milad Avatar asked Feb 10 '26 20:02

Milad


1 Answers

function ExecuteJavascriptString() {
    var n = 0;
    var s = "(true || false) || (true || (true || false)) && true";
    var ifstate = " if (" + s + ") { console.log('done'); } ";
    setTimeout(ifstate, 1);
}

ExecuteJavascriptString()

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!