Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to expression

Tags:

javascript

Is there any way to convert a string to an expression?

my string: var1 == null && var2 != 5

I want to use this string as a condition of the if(), Like if(var1 == null && var2 != 5)

like image 804
Payman Biukaghazadeh Avatar asked Feb 06 '13 09:02

Payman Biukaghazadeh


People also ask

How do you convert a string to an expression?

Convert a String to an Expression in R Programming – parse() Function. parse() function in R Language is used to convert an object of character class to an object of expression class.

How do you convert a string to an expression in Python?

You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.


3 Answers

One option is to create and call new Function:

var strExpr = "var1 == null && var2 != 5";
if (new Function("return " + strExpr)()) {
    // ...
}
like image 141
VisioN Avatar answered Oct 12 '22 08:10

VisioN


Use eval. This will do

if (eval(" var1 == null && var2 != 5"))
{
}
like image 26
999k Avatar answered Oct 12 '22 07:10

999k


To see how eval works, just write in console:

console.log(eval("1==1"));
console.log(eval("1==2"));

This will output true and false

like image 26
TomTom Avatar answered Oct 12 '22 09:10

TomTom