Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert variable string value to expression in JavaScript

Tags:

javascript

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

like image 626
Rahul Sharma Avatar asked Sep 10 '16 13:09

Rahul Sharma


2 Answers

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.

like image 84
Xotic750 Avatar answered Oct 13 '22 22:10

Xotic750


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
like image 24
Bartłomiej Gładys Avatar answered Oct 13 '22 22:10

Bartłomiej Gładys