Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2027
我在风中等你
我在风中等你 2020-11-22 03:34

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?

<
16条回答
  •  [愿得一人]
    2020-11-22 04:12

    An alternative to the excellent answer by @kennebec, using a shorter regular expression and allowing spaces between operators

    function addbits(s) {
        var total = 0;
        s = s.replace(/\s/g, '').match(/[+\-]?([0-9\.\s]+)/g) || [];
        while(s.length) total += parseFloat(s.shift());
        return total;
    }
    

    Use it like

    addbits('5 + 30 - 25.1 + 11');
    

    Update

    Here's a more optimised version

    function addbits(s) {
        return (s.replace(/\s/g, '').match(/[+\-]?([0-9\.]+)/g) || [])
            .reduce(function(sum, value) {
                return parseFloat(sum) + parseFloat(value);
            });
    }
    

提交回复
热议问题