-1

Can anybody tell me how to convert math operation which is in string to int and get the result? For example give string "2 + 3 * 4 - 5" to function and get correct result. Any tips how to do it?

Thank You :)

I tried to use split and join method but nothing good happend

Gaultier89
  • 29
  • 3
  • Can [this](https://stackoverflow.com/questions/13077923/how-can-i-convert-a-string-into-a-math-operator-in-javascript) be of help? – Tommi Oct 31 '22 at 08:04
  • 2
    I think what you want to do is use eval() as @Tommi is suggesting. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval – Chris Oct 31 '22 at 08:07

1 Answers1

2

You need to build an abstract syntax tree (AST) and iterate over the tree to get the result.

For example: you can build a tree for an expression "2 + 5 x 4" as follows

enter image description here

Learn more about AST

Extra:

JS AST implementation for math expressions

Math.js has lots of functionalities for parsing math expressions

you can also use JS eval() function but it has some security concerns

Cheers!

Asraf
  • 1,322
  • 2
  • 12