1

I'm getting string representation for es6 function like this

"return (...args) => {↵    console.log('HIGHLIGHTLOADER', args);↵  };"

from this string, I need to create a function

const func = (...args) => {
  console.log('HIGHLIGHTLOADER', args);
} 

Without using eval How can i parse this string?.

7
  • By "parse" - do you mean you want to create an executable function you can directly call? Or by "parse" do you mean you want the AST of the function? If it's the former then no, you cannot. That's exactly what eval is for. And what you're asking is horribly unsafe. Commented Nov 3, 2020 at 9:44
  • Also, why do you want to do this? What is the use-case? Commented Nov 3, 2020 at 9:45
  • @Dai yes I want to create executable function. Commented Nov 3, 2020 at 9:45
  • Why without eval? It's literally made for this use. Commented Nov 3, 2020 at 9:46
  • 1
    @WimalWeerawansa What is the nature of this application? How does it run (in the browser? server-side NodeJS? something else?). Does your application design actually call for the execution of untrusted, unverified user-supplied scripts? How does your program handle someone providing a script that steals cookies and sends them to a criminal botnet or does JavaScript cryptocurrency mining? Commented Nov 3, 2020 at 9:49

1 Answer 1

5

Use the Function constructor (after removing invalid characters like )

const input = "return (...args) => { console.log('HIGHLIGHTLOADER', args); };"
const func = (new Function(input)());

func(1, 2, 3);

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

2 Comments

I note that this approach has the same security issues as eval - so any company policy that forbids eval must also forbid use of the Function(string) constructor.
🠕 This. If you really want to stick with this approach, then only ever use this if you're 100% sure that the content of input will be safe and not controlled by anyone else but you.

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.