Search code examples
javascriptstringmathnumbers

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.


Solution

  • I've eventually gone for this solution, which works for summing positive and negative integers (and with a little modification to the regex will work for decimals too):

    function sum(string) {
      return (string.match(/^(-?\d+)(\+-?\d+)*$/)) ? string.split('+').stringSum() : NaN;
    }   
    
    Array.prototype.stringSum = function() {
        var sum = 0;
        for(var k=0, kl=this.length;k<kl;k++)
        {
            sum += +this[k];
        }
        return sum;
    }
    

    I'm not sure if it's faster than eval(), but as I have to carry out the operation lots of times I'm far more comfortable runing this script than creating loads of instances of the javascript compiler