Salvatore <ar******@wanadoo.fr> writes:
Given an expression f = '2*x+3' from a user input
I would like to do some sort of
function userFunction(x):
return f(x)
is it possible with Javascript ?
This is one of the (very few) cases where you might want to
use the eval function (or the comparable Function constructor).
Just remember that the eval/Function functions understand all
javascript, not just arithmetic expressions, so there is plenty
of rope for a user to hang himself with.
Try this:
var userFunction = Function("x","return ("+f+");");
(by wrapping the value of "f" in "return (...)", you guarantee
that "f" contains an expression, not a full Javascript program.
It doesn't change anything for a determined hacker who wants
to execute arbitrary code, but it catches some accidental
mistypings. Remember: *never* use eval for server-side code!)
/L
--
Lasse Reichstein Nielsen -
lr*@hotpop.com
Art D'HTML: <URL:http://www.infimum.dk/HTML/randomArtSplit.html>
'Faith without judgement merely degrades the spirit divine.'