Matt Cowley Matt Cowley - 20 days ago 7
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
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.

Answer

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