user10496245
user10496245

Reputation: 217

How to eval string function and return value in javascript?

I have a method in string like:

var str = "function evalTest(param){if(param)return '<div>hello</div>'}else return '<div>world</div>'"

I am replacing param like:

 var res = str.replace("param", "param=false");

Now if I do eval like:

var final = eval(res);

I am expecting final should contain result "world" because passed param = false.

How to achieve this result "world"?

Upvotes: 0

Views: 1636

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074435

First a caveat: There's almost certainly a better solution to whatever problem you're trying to solve by having that function in a string.

And another one: Never eval code supplied by an end user except for that same end user. For instance, never let user A supply the code, then eval it in user B's browser. (Without user B knowing that you're doing that and expressly consenting to it.)

Really, almost any time you're reaching for eval (or its cousin new Function), it's worth stepping back to see if there's another approach you can use.


But answering the question asked:

eval is just creating the function. You don't have anything in that string that calls it.

Because eval works magically in the current scope, evaling your string creates the function in the current scope. You could then call your function to get the result you're looking for:

var str = "function evalTest(param){if(param){return '<div>hello</div>'}else {return '<div>world</div>'}}";
var res = str.replace("param", "param=false");
eval(res);
var final = evalTest();
console.log(final);

Note that I fixed a couple of syntax errors in the function's text (curly brace issues, mostly).

If you don't want the function defined in the current scope, you can modify the string to make it a function expression and call it immediately:

var str = "function evalTest(param){if(param){return '<div>hello</div>'}else {return '<div>world</div>'}}";
var res = str.replace("param", "param=false");
var final = eval("(" + res + ")()");
console.log(final);

Upvotes: 2

Related Questions