Matt Cowley Matt Cowley - 1 year ago 135
Javascript Question

JS Check if input string is valid code and run input

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
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
and that would be valid, and I would like to run that, however something like
would be invalid.

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

Answer Source

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');  


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download