If I have a function:
function myfunc(param1, param2, param3) {
// ...
}
and I have a string:
var myCall = "myfunc(1, 'abc', 'true')"
Is there a way to make the function call using the string and include the params? I don't know the number of parameters in advance. I have tried
var func = myCall.substr(0, myCall.indexOf('('));
var args = myCall.substring(myCall.indexOf('(')+1, myCall.length-1);
window[func](args.split(','));
but that just calls the function with an array to the first parameter. How do I split the arguments and pass them in with an unknown number of parameters?
2 Answers 2
You can do this using the Function constructor:
function myfunc(param1, param2, param3) {
console.log(param1, param2, param3);
}
var myCall = "myfunc(1, 'abc', 'true')";
// here the 'myfunc' string indicates the name of a parameter that will
// be passed into the function that new Function is creating.
// i.e., we are going to pass in the myfunc function
// when we actually call myCaller
var myCaller = new Function('myfunc', myCall);
myCaller(myfunc);
Comments
You can use .replace() again with RegExp /\(.*/ to replace all characters except for function name, .replace() with RegExp /^\w+(?=\))|[()]/ to remove function name and parenthesis from string, .match() with RegExp /[\w\d]+/g to match digit or word characters, .map() to return digit or word characters within an array, Function.prototype.apply() to pass array to function call
function myfunc(param1, param2, param3) {
console.log(param1, param2, param3)
}
var myCall = "myfunc(1, 'abc', 'true')";
var fn = myCall.replace(/\(.*/, "");
var params = myCall.replace(/^\w+(?=\))|[()]/, "")
.match(/[\w\d]+/g).map(function(param) {
return /\d/.test(param) ? +param : param
});
window[fn].apply(null, params);
eval(myCall)