1

I have this "2+2" and "(2+5)*2" in JS and wanted convert them into int and calculate to get the result of 4 and 14 respectively. So, concerning the research done, I found convert string to integer and calculate which offers to use eval() which hits performance therefore I wanted to kindly ask what is the right way to convert "2+2" and "(2+5)*2" into int to calculate?

Mir
  • 75
  • 8
  • Other than using `eval` (which you shouldn't for both performance and security reasons), you can only write your own String parser. I'd do neither and make sure I don't have such strings to work with. – connexo Apr 05 '20 at 14:51
  • Can you elaborate on why you have been given this task? Is it a school assignment? – JLRishe Apr 05 '20 at 14:51
  • Although you can use `eval` for this but it is not a good practice to use eval and it has a lot of security issues unless you are sure your string does consist of operators and digits. For eval you can use this: `let calculated = eval('2+2');` But if not it is better to separate digits and operators via regex and then do the operation. – Hirad Nikoo Apr 05 '20 at 14:55
  • @JLRishe, no I was creating calculator in React and wanted to convert that string to something that can be calculated and show the result:) – Mir Apr 05 '20 at 14:57
  • @connexo, thank you for your comments, what do you think about math.js. Is it ok to use that? – Mir Apr 05 '20 at 14:59

1 Answers1

0

You are using eval() correctly in this case as that is what is made for. As per @yckart in this answer, he used the function constructor to evaluate.