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?
1 Answer
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.
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.evalfor 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.