I need to evaluate a custom function passed from the server as a string. It's all part of a complicated json I get, but anyway, I seem to be needing something along the lines:
var customJSfromServer = "return 2+2+2;"
var evalValue = eval(customJSfromServer);
alert(evalValue) ;// should be "6";
Obviously this is not working as I expected. Any way I can achieve this ?
If code contains an expression, eval evaluates the expression and returns its value. If code contains a JavaScript statement or statements, eval( ) executes those statements and returns the value, if any, returned by the last statement. If code does not return any value, eval( ) returns undefined .
eval() returns the completion value of statementsFor if , it would be the last expression or statement evaluated. The following example uses eval() to evaluate the string str .
An alternative to eval is Function() . Just like eval() , Function() takes some expression as a string for execution, except, rather than outputting the result directly, it returns an anonymous function to you that you can call. `Function() is a faster and more secure alternative to eval().
In other words, it's seen as a variable defined in the body of eval() . You can use x in expression , and eval() will have access to it. In contrast, if you try to use y , then you'll get a NameError because y isn't defined in either the globals namespace or the locals namespace.
The first method is to delete return keywords and the semicolon:
var expression = '2+2+2';
var result = eval('(' + expression + ')')
alert(result);
note the '(' and ')' is a must.
or you can make it a function:
var expression = 'return 2+2+2;'
var result = eval('(function() {' + expression + '}())');
alert(result);
even simpler, do not use eval:
var expression = 'return 2+2+2;';
var result = new Function(expression)();
alert(result);
If you can guarantee the return
statement will always exist, you might find the following more appropriate:
var customJSfromServer = "return 2+2+2;"
var asFunc = new Function(customJSfromServer);
alert(asFunc()) ;// should be "6";
Of course, you could also do:
var customJSfromServer = "return 2+2+2;"
var evalValue = (new Function(customJSfromServer)());
alert(evalValue) ;// should be "6";
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