I know that we can use Math.pow()
as a power function. However I'm making a calculator, and the user might type "^" to do the power function.
Is there any way to use "^" as a power function?
Or some things like ^() will also work.
Asked
Active
Viewed 64 times
1

Broccoliy
- 19
- 2
-
2use `**` instead. – Nina Scholz Jun 20 '22 at 17:41
-
4Don't use `eval` to implement a calculator. Parse the string, then interpret the operators as you see fit. – VLAZ Jun 20 '22 at 17:42
-
You might find [Parse arithmetic expression with javascript](https://stackoverflow.com/questions/23325832/parse-arithmetic-expression-with-javascript) useful. – Andrew Morton Jun 20 '22 at 17:42
-
You could do something like this - `let eqn = "5^6"; Math.pow(eqn.split("^")[0], eqn.split("^")[1])`. There are better ways to parse the string. – CodeWalker Jun 20 '22 at 17:44
-
Okay, I'll look around how to parse the string – Broccoliy Jun 20 '22 at 17:49
-
btw should I use an array to parse or something else? – Broccoliy Jun 20 '22 at 17:59
-
1@Broccoliy You might tokenize into an array, but in the end you will need a parse *tree* – Bergi Jun 20 '22 at 22:08
1 Answers
2
Sorry, ^
means binary-exclusive-or in Javascript, and Javascript does not allow you to re-map operators.
(And you shouldn’t anyway. It would quickly become very confusing.)

Michael Lorton
- 43,060
- 26
- 103
- 144