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

Posted by brainjam on Stack Overflow See other posts from Stack Overflow or by brainjam
Published on 2010-04-04T04:19:12Z Indexed on 2010/04/04 4:23 UTC
Read the original article Hit count: 538

Filed under:

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?

© Stack Overflow or respective owner

Related posts about JavaScript