1

So I really couldn't find much on this. The idea is that I have a user input (text) and I want to check if its valid code in JS and then run it if it is.

I know that I can do if (typeof userInput === "function") { if the userInput was actually a function, but the user input is just a string input at this point, so I'm quite stuck, and it also contains any arguments or other code.

As an example, the input may be "alert('test')" and that would be valid, and I would like to run that, however something like "madeUpFunction(lol)" would be invalid.

I'm happy if I can just get functions working and not any JS code.

Matt Cowley
  • 2,164
  • 2
  • 18
  • 29

3 Answers3

2

You can extract the string up until the first ( in order to get the function name, and then test that it exists using typeof eval(funcName). Then use the Function constructor to make sure that the syntax is valid for the rest of the arguments without actually executing the code.

You can then return the function which executes what the user entered, but note that there may be security issues if you decide to execute the function.

function parseFunctionCall(str) {
  var funcName = str.slice(0, str.indexOf('('));
  if (typeof eval(funcName) === 'function') {
    return new Function(str);
  } else {
    throw new Error('Invalid function name');  
  }
}

console.log(parseFunctionCall("console.log('hi')"));
4castle
  • 32,613
  • 11
  • 69
  • 106
  • This is great, thank you! However if I input `console.log('test')` it doesn't detect it? – Matt Cowley Nov 17 '16 at 18:33
  • That's because `console.log` is selecting a function that isn't directly on `window`. I've updated to use `eval`, but [there are more efficient ways to do it](http://stackoverflow.com/q/6491463/5743988). – 4castle Nov 17 '16 at 18:40
0

You can use eval("typeof "+ input) to achieve what you want. The argument of the eval() function is a string. If the string represents an expression, eval() evaluates the expression.

var myFunc = function(){};
var input = prompt('Enter input string');

if(eval("typeof "+input) === "function"){
 document.getElementById('d1').innerHTML = "Yes it's a funtion";
}

else{
  document.getElementById('d1').innerHTML = "Not a funtion";
}
  
<div id="d1">

</div>
Adarsh Singhal
  • 362
  • 1
  • 3
  • 12
-1

Assuming this is in a browser and that that function you want to check is in the global scope:

if (typeof window[userInput] === "function" ) {
    ...
}
Chris Charles
  • 4,406
  • 17
  • 31