I have reservations about allowing users to input function names, but for the sake of discussion, let's say you have the function name stored in a variable and the argument value in another variable. Here's how you could go about it:
var myString = window[fn](arg);
The argument arg
is likely already passed as an argument, making that part straightforward. The challenge lies in extracting the function name. A simple regex solution could be:
var fn = /^([a-z0-9_]+)\(arg\)$/i.exec(str)[1];
if (fn && typeof window[fn] === 'function') {
window[fn](arg);
}
This code assumes that the function always exists in the global scope. If not, adjustments will need to be made. Additionally, keep in mind that the regex provided may not cover all possible function names.
If you wish to restrict the string to specific functions (which is advisable), this can be achieved once you have the function name:
var allowedFunctions = {fn1: fn1, fn2: fn2, someOtherFunction: function() {} },
fn = /^([a-z0-9_]+)\(arg\)$/i.exec(str)[1];
if (fn && allowedFunctions[fn]) {
allowedFunctions[fn](arg);
} else {
// Nice try.
}
(Note that if arg
is not a variable name but rather a literal or complex expression, the process becomes more intricate and less secure.)