Say I've got a Javascript string like the following
var fnStr = "function(){blah1;blah2;blah3; }" ;
(This may be from an expression the user has typed in, duly sanitized, or it may be the result of some symbolic computation. It really doesn't matter).
I want to define fn
as if the following line was in my code:
var fn = function(){blah1;blah2;blah3; } ;
How do I do that?
The best I've come up with is the following:
var fn = eval("var f = function(){ return "+fnStr+";}; f() ;") ;
This seems to do the trick, even though it uses the dreaded eval()
, and uses a slightly convoluted argument. Can I do better? I.e. either not use eval()
, or supply it with a simpler argument?
To convert a string in to function "eval()" method should be used. This method takes a string as a parameter and converts it into a function.
Stringify a JavaScript Object Use the JavaScript function JSON. stringify() to convert it into a string.
Converting Values to Strings Values can be explicitly converted to strings by calling either String() or n. toString() . With the String() function, let's convert a Boolean value to a string by passing the value true into the parameters for String() .
A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.
There's also the Function object.
var adder = new Function("a", "b", "return a + b");
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