-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

2

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.