5

Is there anyway to convert a string to a condition inside if statement:

example:

var condition = "a == b && ( a > 5 || b > 5)";

if(condition) {
    alert("succes");
}
Ayoub k
  • 7,788
  • 9
  • 34
  • 57

5 Answers5

7

A safer alternative to eval() may be Function().

var condition = "4 == 4 && ( 10 > 5 || 9 > 5)";
var evaluate = (c) => Function(`return ${c}`)();

if(evaluate(condition)) {
    alert("succes");
}

Per MDN:

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. More importantly, a third-party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways to which the similar Function is not susceptible.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
2

You can use new function

let a = 6;
let b = 6
var condition = "a == b && ( a > 5 || b > 5)";

let func = new Function('a','b', `return (${condition})` )

if(func(a,b)) {
    alert("succes");
}
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
1

eval can help, but try to avoid using it

let a = 6;
let b = 6
var condition = "a == b && ( a > 5 || b > 5)";

if (eval(condition)) {
  alert("succes");
}
brk
  • 48,835
  • 10
  • 56
  • 78
  • Agreed, no use eval if possible. – Persijn Mar 18 '19 at 15:32
  • @MichaelLeVan https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – brk Mar 18 '19 at 15:34
  • @MichaelLeVan [MDN: **Do not ever use `eval()`!**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!) – Tyler Roper Mar 18 '19 at 15:34
0

use eval :

var condition = "4 == 4 && ( 10 > 5 || 9 > 5)";

if(eval(condition)) {
    alert("succes");
}
Aziz.G
  • 3,599
  • 2
  • 17
  • 35
  • There's a reason [eval is shunned](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Do_not_ever_use_eval!). – Chris W. Mar 18 '19 at 15:32
0

Convert your data and condition to JSON

Then set the condition by hand:

var json = '{"a":20, "b":20, "max":5}'; //Max is your condition
var data = JSON.parse(json);
var a = data.a;
var b = data.b;
var max = data.max;

if(a == b && ( a > 5 || b > 5)) {
    console.log("foobar");
}
Persijn
  • 14,624
  • 3
  • 43
  • 72