3

suppose I have the following code:

    var str = "4*(3)^2/1"

Is the simplest solution just to make a stack of the operators and solve with postfix notation? Or is there a really basic solution I'm missing.

Additionally how can I adapt if I'm using log, ln, sin, cos, and tan?

3 Answers 3

5

Sorry to respond to my own question, but the easiest solution is using math.js

    var ans = math.eval(str);
Sign up to request clarification or add additional context in comments.

1 Comment

Answers should contain a solution. This is merely a suggestion to use a library to solve a problem. Maybe show how to use the library instead of just linking to it.
4

The simplest yet a bit dangerous so you may have to validate (clean) an expression before evaluating is using eval (for exponent-operator ^, replace it with the exponent-operator in JavaScript **):

var str="4*(3)^2/1".replace(/\^/g,'**');
console.log(eval(str));

And for special functions such as sin, cos, exp and so on, create a function of your own using the corresponding predefined function in JavaScript:

var str="4*(3)^2/1+(exp(5)*cos(14)^(1/sin(13)))^2".replace(/\^/g,'**');
function sin(x) { return Math.sin(x) }
function cos(x) { return Math.cos(x) }
// so on
function exp(x) { return Math.exp(x) }
console.log(eval(str));

2 Comments

What about ^?
@ringø I edited the answer, you basically replace the ^ with ** since the latter does exponentiation.
2

You do not need postfix notation. You can use eval method.

var str = "4*(3)^2/1";
console.log(str);
console.log(eval(str));

Also, another solution is using javascript-expression-evaluator which allows you to do stuff like:

Parser.evaluate("2 ^ x", { x: 4 });

3 Comments

be very cautious with what you pass as paramter. If the expression is from the clent, be sure to sanitize it properly.
OP probably sees ^2 as square, not XOR 2
should I use Math.pow() instead then?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.