Wimal Weerawansa
Wimal Weerawansa

Reputation: 157

Javascript parse string as es6 function

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?.

Upvotes: 1

Views: 365

Answers (1)

Andreas
Andreas

Reputation: 21881

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

Upvotes: 5

Related Questions