1

In JavaScript, is there any way to create function object from function definition in a String?

Something similar to a JSON.parse for creating JSON from a String.

const parseFunction = (str)=> {
   // What should be implemented here?
   return func;
}
let funStr = parseFunction("function replacer(arg1) {console.log(arg1)}");
4
  • 1
    Do you mean eval? Commented Jun 9, 2021 at 11:33
  • Why do you need this? Where is the function definition coming from? Commented Jun 9, 2021 at 11:34
  • 2
    You could use the Function constructor? new Function(str)? Just pass the function body instead Commented Jun 9, 2021 at 11:40
  • @felix-kling working on a JSON template based dashboard configuration.. couldn't find a better validator(lints) that accepts function as a value for a key.. also having function inside JSON makes it as an invalid JSON.. I want to hold function as value and also a valid JSON. So, just looking for options Commented Jun 9, 2021 at 11:56

2 Answers 2

1

Using eval invites a lot of security risks in your application. Javascript now has a alternative to that here

const parseFunction = (str)=> {
   return Function('"use strict";return (' + str + ')')();
}
let funStr = parseFunction("function(arg1) {console.log(arg1)}");

You try playing around it this is just for reference.

Sign up to request clarification or add additional context in comments.

1 Comment

Just to make sure that people don't get the wrong impression: The only difference between direct eval and Function()() is the fact that the latter executes the code in global scope. There isn't anything else that makes it fundamentally more secure.
1

Just improvising Mr.@abhishek-sharma answer,

The function created using Function('"use strict";return (' + str + ')')(); will not be closure of current scope. In case if anyone want to access some variable in the current scope,

const parseFunction = (str) => {
  return Function(
    'varNameInStr',
    'return function() {return (' + str + ')}',
  )(varInCurrScope)();
};
parseFunction("function(){console.log(varNameInStr)}")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.