Yes, using Function is a great solution, but we can go a little further and prepare a universal parser that parses the string and converts it into a real JavaScript function ...
if (typeof String.prototype.parseFunction != 'function') { String.prototype.parseFunction = function () { var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi; var match = funcReg.exec(this.replace(/\n/g, ' ')); if(match) { return new Function(match[1].split(','), match[2]); } return null; }; }
examples of using:
var func = 'function (a, b) { return a + b; }'.parseFunction(); alert(func(3,4)); func = 'function (a, b) { alert("Hello from function initiated from string!"); }'.parseFunction(); func();
here is jsfiddle
Alex Wheatman Nov 13 '14 at 20:37 2014-11-13 20:37
source share