Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate boolean expression in a string in Javascript without eval

I have a string that contains Boolean logic, something along the lines of:

((true && true) || false && !true)

What is the best way in Javascript to safely evaluate this string to get the boolean result? I would like to avoid using eval().

like image 245
dfj Avatar asked Dec 06 '15 15:12

dfj


People also ask

What can I use instead of eval in JavaScript?

An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().

How do you evaluate a string expression in JavaScript?

The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.

Why we should not use eval in JavaScript?

eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() 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.

Why is eval harmful?

Malicious code : invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username. Terribly slow : the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings!


Video Answer


1 Answers

I wrote this boolean string parser for another question:

var exp1 = "(true && true || false) && (true || (false && true))";
var exp2 = "((true && true) || false && !true)";
var exp3 = "(true && !false) && true && !false";
var exp4 = "(a && b) && c && d";

console.log(exp1 + ' = ' + parseBoolStr(exp1));
console.log(exp2 + ' = ' + parseBoolStr(exp2));
console.log(exp3 + ' = ' + parseBoolStr(exp3));
console.log(exp4 + ' = ' + parseBoolStr(exp4));

function parseBoolStr(str) {
  var expressions = {};
  var expressionRegex = new RegExp("\\((?:(?:!*true)|(?:!*false)|(?:&&)|(?:\\|\\|)|\\s|(?:!*\\w+))+\\)");
  var expressionIndex = 0;
  str = str.trim();
  while (str.match(expressionRegex)) {
    var match = str.match(expressionRegex)[0];
    var expression = 'boolExpr' + expressionIndex;
    str = str.replace(match, expression);
    match = match.replace('(', '').replace(')', '');
    expressions[expression] = match;
    expressionIndex++;
  }
  return evalBoolStr(str, expressions);
}

function evalBoolStr(str, expressions) {
  var conditions = str.split(' ');
  if (conditions.length > 0) {
    var validity = toBoolean(conditions[0], expressions);
    for (var i = 1; i + 1 < conditions.length; i += 2) {
      var comparer = conditions[i];
      var value = toBoolean(conditions[i + 1], expressions);
      switch (comparer) {
        case '&&':
          validity = validity && value;
          break;
        case '||':
          validity = validity || value;
          break;
      }
    }
    return validity;
  }
  return 'Invalid input';
}

function toBoolean(str, expressions) {
  var inversed = 0;
  while (str.indexOf('!') === 0) {
    str = str.replace('!', '');
    inversed++;
  }
  var validity;
  if (str.indexOf('boolExpr') === 0) {
    validity = evalBoolStr(expressions[str], expressions);
  } else if (str == 'true' || str == 'false') {
    validity = str == 'true';
  } else {
    validity = window[str]();
  }
  for (var i = 0; i < inversed; i++) {
    validity = !validity;
  }
  return validity;
}

function a() {
  return false;
}
function b() {
  return true;
}
function c() {
  return true;
}
function d() {
  return false;
}

Functions a, b, c and d can, and should, be removed. Just an example.

Usage: parseBoolStr('((true && true) || false && !true)');

like image 147
Arg0n Avatar answered Oct 18 '22 03:10

Arg0n