Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a string describing a Javascript function, convert it to a Javascript function

Tags:

javascript

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?

like image 361
brainjam Avatar asked Apr 04 '10 04:04

brainjam


People also ask

How do you convert a string to a function?

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.

Which function is used to convert a JavaScript object into a string?

Stringify a JavaScript Object Use the JavaScript function JSON. stringify() to convert it into a string.

How do you convert something to a string in JavaScript?

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() .

What is function () () in JavaScript?

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.


1 Answers

There's also the Function object.

var adder = new Function("a", "b", "return a + b"); 
like image 62
goat Avatar answered Sep 30 '22 16:09

goat