Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating a string as a mathematical expression in JavaScript

How do I parse and evaluate a mathematical expression in a string (e.g. '1+1') without invoking eval(string) to yield its numerical value?

With that example, I want the function to accept '1+1' and return 2.

like image 753
wheresrhys Avatar asked Feb 16 '10 20:02

wheresrhys


People also ask

How do you evaluate a string expression in JavaScript?

The eval() function in JavaScript is used to evaluate the expression. It is JavaScirpt's global function, which evaluates the specified string as JavaScript code and executes it. The parameter of the eval() function is a string. If the parameter represents the statements, eval() evaluates the statements.

How can I convert a string into a math operator in JavaScript?

var myString = "225 + 15 - 10" var newString = myString. split(" "); This would turn myString into an array: ["225", "+", "15", "-", "10"];

Can you do math with strings in JavaScript?

Strings and Mathematical Operators With string + is used for concatenation. For example, 'JS is' + ' fun'; results in 'JS is fun' .


2 Answers

You can use the JavaScript Expression Evaluator library, which allows you to do stuff like:

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

Or mathjs, which allows stuff like:

math.eval('sin(45 deg) ^ 2'); 

I ended up choosing mathjs for one of my projects.

like image 167
Rafael Vega Avatar answered Sep 29 '22 08:09

Rafael Vega


You can do + or - easily:

function addbits(s) {    var total = 0,        s = s.match(/[+\-]*(\.\d+|\d+(\.\d+)?)/g) || [];            while (s.length) {      total += parseFloat(s.shift());    }    return total;  }    var string = '1+23+4+5-30';  console.log(    addbits(string)  )

More complicated math makes eval more attractive- and certainly simpler to write.

like image 45
kennebec Avatar answered Sep 29 '22 07:09

kennebec