T
T
timoninas12021-05-28 00:22:32
JavaScript
timoninas1, 2021-05-28 00:22:32

How to do string calculation in JS?

What function should be written in JS to evaluate the following expressions?

"'2 + 2" -> 4

"(3 + 7) / (5 - (2 + 1))" -> 5

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Karo, 2021-05-28
@timoninas1

1) In the forehead and the least safe - eval
2) A little more confusing - we wrap it in a function through new Function
3) Confusing, but interesting - parse the string, split it into operators and operands and count it all, taking into account the priority of operators and brackets
4) Boring and ordinary - we take a library like mathjs and feed it

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question