0

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"?

2
  • 1
    This is very dangerous. You should read this. Commented Dec 20, 2018 at 16:57
  • "I have a method in string like" Whatever problem you're trying to solve by doing that, there's almost certainl a better way to solve it. You might consider posting a question about that problem. Commented Dec 20, 2018 at 17:01

1 Answer 1

2

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.