javascript - JS Check if input string is valid code and run input -
so couldn't find on this. idea have user input (text) , want check if valid code in js , run if is.
i know can if (typeof userinput === "function") {
if userinput
function, user input string input @ point, i'm quite stuck, , contains arguments or other code.
as example, input may "alert('test')"
, valid, , run that, "madeupfunction(lol)"
invalid.
i'm happy if can functions working , not js code.
you can extract string until first (
in order function name, , test exists using typeof eval(funcname)
. use function
constructor make sure syntax valid rest of arguments without executing code.
you can return function executes user entered, note there may security issues if decide execute 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')"));
Comments
Post a Comment