1

I have a set of strings coming from my server-side api in the format:

  "`Employee age is ${employeeAge}`"

I want to evaluate this string in a function which has reference to 'employeeAge'.

The possible ways are to use eval() :

 const employeeAge = 34;
 const string = eval("`Employee age is ${employeeAge}`")

expected result = "Employee age is 34"

or using [new Function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function method

Is there any way to avoid using these methods?

Thanks

vedant sali
  • 80
  • 2
  • 5
  • 17
  • 1
    Parse it yourself? – jfriend00 Feb 02 '18 at 05:21
  • Where would the value of `employeeAge` come from without `eval`? `eval` is the only way to access random variables in a scope by name. – loganfsmyth Feb 02 '18 at 05:23
  • please read the question again. I have updated it – vedant sali Feb 02 '18 at 05:27
  • I think this is one of the few appropriate uses of `eval`, IF you sanitise and trust the input. The alternative would be to run a parser through it which you pass an object with the keys that may be referenced – coagmano Feb 02 '18 at 05:31
  • 2
    Yeah my suggestion would be parse it with an ES6 parser to validate that it is only a template literal with variable names, and then run it with `new Function` and explicitly pass in every variable you want to expose to ensure. – loganfsmyth Feb 02 '18 at 05:38
  • https://stackoverflow.com/a/31999948/4554754 this solution looks quite good – vedant sali Feb 02 '18 at 05:56

0 Answers0