Jamie Alizadeh
Jamie Alizadeh

Reputation: 159

Solve an arithmetic string in javascript?

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?

Upvotes: 3

Views: 985

Answers (3)

Djaouad
Djaouad

Reputation: 22776

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));

Upvotes: 4

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48407

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 });

Upvotes: 2

Jamie Alizadeh
Jamie Alizadeh

Reputation: 159

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

    var ans = math.eval(str);

Upvotes: 5

Related Questions