0

How to do arithmetic operation in group values using javascript for example

var a = "5(8)+109/100";

I have used javascript eval() function to solve this,

Output :

var output = eval(a); //41.09

But eval() is not correct solution. Is there anything alternate solution to solve this task

User can type in this textbox

Vijaykarthik
  • 333
  • 4
  • 10
  • 25
  • 4
    This example is strange. "5(8)" ? – Denys Séguret Dec 07 '17 at 12:31
  • A correct solution would likely involve creating abstract syntax trees. – alistaircol Dec 07 '17 at 12:33
  • Why is `eval` not the correct solution (assuming the about equivalent Function alternative has been considered) ? Some context is missing here, like for example how the formula to compute is produced. If what you want is a secure math formula parser, just use a lib. – Denys Séguret Dec 07 '17 at 12:33
  • I have tried fully with this eval() function only. But for security issue we wont use eval() function. I have searched in google about this, https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea Can i have any lib for my references ? – Vijaykarthik Dec 07 '17 at 12:35
  • @alistaircol can i have any example related to this task ? – Vijaykarthik Dec 07 '17 at 12:38
  • Well you can parse it to make sure it is just numbers and arithmetic operators before you eval() – epascarello Dec 07 '17 at 12:43
  • @epascarello I dont want to use eval() function. – Vijaykarthik Dec 07 '17 at 12:48
  • Than you are going to have to build a parser. Have fun. You can use eval for it, just need to validate the data that it is valid before you run it. – epascarello Dec 07 '17 at 12:50
  • yes bro i accept your answer, have to validate before eval. But this eval() has been remove due to security issue. so i can't use this eval function. so what asking is there any alternate solution to solve above task – Vijaykarthik Dec 07 '17 at 12:57
  • What removed eval()? You can use `new Function()` but that is just like eval() or you can write a parser... AKA you write code that solves it just like you would if you did it by hand. – epascarello Dec 07 '17 at 12:58

1 Answers1

0

Try following:

var a = "5(8)+109/100"; var res = ( new Function( 'return ' + a.split('(').join('*(') ) )(); console.log(res);

Shyam
  • 1,364
  • 7
  • 13