5

i am trying to convert a string value to expression so that i can use it in if condition like:

var StringVal = '20 > 18 && "yes" == "yes"';

if(StringVal){

    ....
}

is it possible to do this, please suggest me.

Thanks

Xotic750
  • 22,914
  • 8
  • 57
  • 79
Rahul Sharma
  • 622
  • 7
  • 25
  • [`eval`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/eval) would do it, or most likely the `Function` equivalent. – Xotic750 Sep 10 '16 at 13:04
  • yes..but it will not work for `"yes" == "yes"` – Rahul Sharma Sep 10 '16 at 13:05
  • 1
    Why do you need to do this? – Xotic750 Sep 10 '16 at 13:06
  • i am working on some survey app and from web service i am getting: `[[abc]] > 18 && [[xyz]] == "yes"` [[abc]] and [[xyz]] stands from previous questions answer and i just replace that [[..]] string to real values and after that i have to check the condition.. – Rahul Sharma Sep 10 '16 at 13:10
  • i think eval is working... – Rahul Sharma Sep 10 '16 at 13:10
  • Eval would work but you shouldn't use it. Why can't you store the previous answers? – spongessuck Sep 10 '16 at 13:11
  • yes i stored in localstorage, so that i am able to replace with the real values..but after all that on last i have to run the condition according it – Rahul Sharma Sep 10 '16 at 13:13
  • Suppose real values are: questID: abc, Value: 20 questID: xyz, Value: 'No' and i just replace in `20 > 18 && No == Yes` – Rahul Sharma Sep 10 '16 at 13:14
  • If you have the values, I'm not sure why you can't use assign them to variables: `abcValue > 18 && xyzValue == "yes"`. This is far better than using `eval`. – spongessuck Sep 10 '16 at 13:16
  • If you use `eval` someone could type in `location.href="someothersite.com"` and your script would execute it, causing it to navigate away! – spongessuck Sep 10 '16 at 13:17

3 Answers3

7

It's not generally safe to take input from a user source and evaluate it, but you could use Function evaluation, or eval

var StringVal = '20 > 18 && "yes" == "yes"';
if (new Function('return (' + StringVal + ')')()) {
  console.log('ok');
}

Are eval() and new Function() the same thing?

Update: If you could give further information in your question as to why you feel this is necessary along with an example of your actual code, then a safer solution could be suggested.

Further: In JSON2, eval is used in JSON.parse

https://github.com/douglascrockford/JSON-js/blob/master/json2.js#L491

but you will also notice that some sanitising is performed before eval is called.

Community
  • 1
  • 1
Xotic750
  • 22,914
  • 8
  • 57
  • 79
3

You can use function eval()

try this:

var StringVal = '20 > 18 && "yes" == "yes"';

if(eval(StringVal)){

    ....
}

other example:

var a = '1==3'
var b = '1==1'

console.log(eval(a));
// false
console.log(eval(b));
// true
Bartłomiej Gładys
  • 4,525
  • 1
  • 14
  • 24
2

Note that eval won't directly parse your text as an expression, e.g.

eval('{}'); // undefined

That's because {} is parsed as a block, not as an object initializer expression.

There are several ways to force it to be parsed as an expression, like nesting inside parentheses, or via a return statement. So I would use

function evalExpr(expr) {
  Function("return " + expr + ";");
  return eval("(" + expr + ")");
}
console.log(evalExpr('{}')); // Object {}
try { evalExpr('1),(2') } catch(err) { console.error(err); } // SyntaxError
try { evalExpr('1;2') } catch(err) { console.error(err); } // SyntaxError

eval("(" + expr + ")") evaluates as an expression, and previously Function("return " + expr + ";") checks that the expression does not contain an invalid ) to escape the wrapping parentheses.

Oriol
  • 274,082
  • 63
  • 437
  • 513