Parsing a function in string

Hello everyone!

How to parse a function in string to be evaluated like a usual function. i.e.

"function myFunc() { return 1 + 2 }" <------ string


function myFunc() { return 1 + 2 } <------ function

I heard about using eval() or Function constructor but they seem to be dangerous as said in MDN doc.

I’m using React.

Thank you!

I think a function constructor is your best bet. It’s much better than eval according to MDN:

“However, there (thankfully) exists a very good alternative to eval: simply using window.Function.”

Would JSON.parse() work?

This function only parse JSON string not function string.

Function forces me to extract arguments and the body of thefunction. :confused: