+ 6

Running code with eval() from user input

So I'm a bit of a noob when it comes to web langauges, but I've read online that I can use the eval() method to basically run code as a string. My question is, can I return a string for the eval function to be equal to? And can I RUN an actual function inside the string? Example: var x = eval("function run(){ var input = "test"; return input;}"); // My hope/want is that x would be equal to "test" * the idea is that the user writes code, and I evaluate it to see if the resulted input is what was expected. *

8th Apr 2017, 8:30 PM
Rrestoring faith
Rrestoring faith - avatar
2 ответов
+ 10
Your example code string evaluate only the declaration of the function, but don't run it... You'll need something like: user_input = "function run() { var input = 'test'; return input;}"; var x = eval(user_input+" run();"); ... or, if you don't know the name of user function to run and/or want let him start his code by his own way, encapsulate the user code in a self running anonymized function: user_input = "function run() { var input = 'test'; return input;}"; var x = eval("("+user_input+" )();"); user_input = "function a() { return 'test'; } function b() { input=a(); return input; } b();"; var x = eval("(function(){ "+user_input+" })();");
8th Apr 2017, 8:05 PM
visph
visph - avatar
+ 5
@visph Thanks, it worked like a charm!
8th Apr 2017, 8:12 PM
Rrestoring faith
Rrestoring faith - avatar