Evaluating a string as a mathematical expression in JavaScript

前端 未结 16 2043
我在风中等你
我在风中等你 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:14

    You could use a for loop to check if the string contains any invalid characters and then use a try...catch with eval to check if the calculation throws an error like eval("2++") would.

    function evaluateMath(str) {
      for (var i = 0; i < str.length; i++) {
        if (isNaN(str[i]) && !['+', '-', '/', '*', '%', '**'].includes(str[i])) {
          return NaN;
        }
      }
      
      
      try {
        return eval(str)
      } catch (e) {
        if (e.name !== 'SyntaxError') throw e
        return NaN;
      }
    }
    
    console.log(evaluateMath('2 + 6'))

    or instead of a function, you could set Math.eval

    Math.eval = function(str) {
      for (var i = 0; i < str.length; i++) {
        if (isNaN(str[i]) && !['+', '-', '/', '*', '%', '**'].includes(str[i])) {
          return NaN;
        }
      }
      
      
      try {
        return eval(str)
      } catch (e) {
        if (e.name !== 'SyntaxError') throw e
        return NaN;
      }
    }
    
    console.log(Math.eval('2 + 6'))

提交回复
热议问题