Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate string giving boolean expression in JavaScript

I have a string that contains Boolean logic something like:

var test = "(true)&&(false)&&!(true||true)"

What is a good way to evaluate this string in JavaScript to get the boolean value of false in this case

  1. I know we could use eval() or new Function().. - but is that a safe approach?
  2. I am guessing the other option would be to write a custom parser. Being a fairly new person to JS, would that be a lot of effort? I could not find any examples of parsers for Boolean logic expressions
  3. Any other alternatives?
like image 962
akoy Avatar asked Apr 01 '16 05:04

akoy


1 Answers

As long as you can guarantee it to be safe, I think you could use eval.

Maybe by treating it before doing an eval?

var test = "(true)&&(false)&&!(true||true)" 

var safe = test.replace(/true/ig, "1").replace(/false/ig, "0");

var match = safe.match(/[0-9&!|()]*/ig);

if(match) {
   var result = !!eval(match[0]);
}
like image 133
loxxy Avatar answered Oct 05 '22 03:10

loxxy