Is there a way to create a function from a string with javascript?

JavascriptStringFunction

Javascript Problem Overview


For example;

var s = "function test(){
  alert(1);
}";

var fnc = aMethod(s);

If this is the string, I want a function that's called fnc. And fnc(); pops alert screen.

eval("alert(1);") doesnt solve my problem.

Javascript Solutions


Solution 1 - Javascript

A better way to create a function from a string is by using Function:

var fn = Function("alert('hello there')");
fn();

This has as advantage / disadvantage that variables in the current scope (if not global) do not apply to the newly constructed function.

Passing arguments is possible too:

var addition = Function("a", "b", "return a + b;");
alert(addition(5, 3)); // shows '8'

Solution 2 - Javascript

I added a jsperf test for 4 different ways to create a function from string :

  • Using RegExp with Function class

    var func = "function (a, b) { return a + b; }".parseFunction();

  • Using Function class with "return"

    var func = new Function("return " + "function (a, b) { return a + b; }")();

  • Using official Function constructor

    var func = new Function("a", "b", "return a + b;");

  • Using Eval

    eval("var func = function (a, b) { return a + b; };");

http://jsben.ch/D2xTG

2 result samples: enter image description here enter image description here

Solution 3 - Javascript

You're pretty close.

//Create string representation of function
var s = "function test(){  alert(1); }";

//"Register" the function
eval(s);

//Call the function
test();

Here's a working fiddle.

Solution 4 - Javascript

Yes, using Function is a great solution but we can go a bit further and prepare universal parser that parse string and convert it to 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 usage:

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

Solution 5 - Javascript

#Dynamic function names in JavaScript

##Using Function

var name = "foo";
// Implement it
var func = new Function("return function " + name + "(){ alert('hi there!'); };")();
// Test it
func();
// Next is TRUE
func.name === 'foo'

Source: http://marcosc.com/2012/03/dynamic-function-names-in-javascript/

##Using eval

var name = "foo";
// Implement it
eval("function " + name + "() { alert('Foo'); };");
// Test it
foo();
// Next is TRUE
foo.name === 'foo'

##Using sjsClass

https://github.com/reduardo7/sjsClass

Example
Class.extend('newClassName', {
    __constructor: function() {
        // ...
    }
});

var x = new newClassName();
// Next is TRUE
newClassName.name === 'newClassName'

Solution 6 - Javascript

This technique may be ultimately equivalent to the eval method, but I wanted to add it, as it might be useful for some.

var newCode = document.createElement("script");

newCode.text = "function newFun( a, b ) { return a + b; }";

document.body.appendChild( newCode );

This is functionally like adding this <script> element to the end of your document, e.g.:

...

<script type="text/javascript">
function newFun( a, b ) { return a + b; }
</script>

</body>
</html>

Solution 7 - Javascript

Use the new Function() with a return inside and execute it immediately.

var s = `function test(){
  alert(1);
}`;

var new_fn = new Function("return " + s)()
console.log(new_fn)
new_fn()

Solution 8 - Javascript

An example with dynamic arguments:

let args = {a:1, b:2}
  , fnString = 'return a + b;';

let fn = Function.apply(Function, Object.keys(args).concat(fnString));

let result = fn.apply(fn, Object.keys(args).map(key=>args[key]))

Solution 9 - Javascript

If you have a function expression that is in string form and you want to make it a function, then you need to include a return statement in the string you pass to new Function.

const strFn = "const sum = (a, b) => a + b"

const newFn = new Function(`${strFn}; return sum`)();

console.log(newFn(2, 3)) // 5

If you don't execute immediately, you can use the function.call method to execute. Remember the first argument it takes is the this value

const newFn = new Function('const arrMultiplier = (arr) => arr.map(num => num * 2); return arrMultiplier')
console.log(newFn.call({}).call({}, [6, 4, 1, 0])); // [12, 8, 2, 0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionymutluView Question on Stackoverflow
Solution 1 - JavascriptLekensteynView Answer on Stackoverflow
Solution 2 - JavascriptphnahView Answer on Stackoverflow
Solution 3 - JavascriptJames HillView Answer on Stackoverflow
Solution 4 - JavascriptMr. PumpkinView Answer on Stackoverflow
Solution 5 - JavascriptEduardo CuomoView Answer on Stackoverflow
Solution 6 - JavascriptDavid NewberryView Answer on Stackoverflow
Solution 7 - JavascriptFernando CarvajalView Answer on Stackoverflow
Solution 8 - JavascriptbrunettdanView Answer on Stackoverflow
Solution 9 - JavascriptChukwualuka ChiamaView Answer on Stackoverflow