Payman Biukaghazadeh
Payman Biukaghazadeh

Reputation: 237

Converting string to expression

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)

Upvotes: 10

Views: 21944

Answers (5)

Giancarlo
Giancarlo

Reputation: 161

The String() function converts the value of an object to a string, you can do eval(String)

<html>
<head>
<script>
function myFunction(){
    var var1 = new String("999 888");
    var var2 = "5";
    var var3;
    var var4 = 8;
    document.write(String(var2)+ "<br>");
    document.write(String(var4)+ "<br>");

    //5
    //8

    if(var3 === undefined && var2 != 6){
            alert('var1='+var1+' var2='+var2);
    }
    var ev=eval(String(var3 === undefined && var2 != 6));
    alert(ev);

    var ev1=eval("var3 === undefined && var2 != 6");
    alert(ev1);

}
</script>
</head>
<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>

Try it and good luck!

Upvotes: 0

999k
999k

Reputation: 6565

Use eval. This will do

if (eval(" var1 == null && var2 != 5"))
{
}

Upvotes: 19

Marc Fischer
Marc Fischer

Reputation: 1306

1.) Java and Javascript don't have much in common, but the name and some syntax inherited from C.

2.) Anyhow, you generally should avoid what you are trying to do. In most languages and cases this practice should not be used due to security problems.

Upvotes: 0

TomTom
TomTom

Reputation: 1885

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

Upvotes: 3

VisioN
VisioN

Reputation: 145398

One option is to create and call new Function:

var strExpr = "var1 == null && var2 != 5";
if (new Function("return " + strExpr)()) {
    // ...
}

Upvotes: 7

Related Questions