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)
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.
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.
One option is to create and call new Function
:
var strExpr = "var1 == null && var2 != 5";
if (new Function("return " + strExpr)()) {
// ...
}
Use eval
. This will do
if (eval(" var1 == null && var2 != 5"))
{
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With