Evaluating a string as a mathematical expression in JavaScript

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

    Somebody has to parse that string. If it's not the interpreter (via eval) then it'll need to be you, writing a parsing routine to extract numbers, operators, and anything else you want to support in a mathematical expression.

    So, no, there isn't any (simple) way without eval. If you're concerned about security (because the input you're parsing isn't from a source you control), maybe you can check the input's format (via a whitelist regex filter) before passing it to eval?

    0 讨论(0)
  • 2020-11-22 04:27

    Simple and elegant with Function()

    function parse(str) {
      return Function(`'use strict'; return (${str})`)()
    }
    
    parse("1+2+3"); 

    0 讨论(0)
  • 2020-11-22 04:27

    I believe that parseInt and ES6 can be helpful in this situation

    let func = (str) => {
      let arr = str.split("");
      return `${Number(arr[0]) + parseInt(arr[1] + Number(arr[2]))}`
    };
    
    console.log(func("1+1"));

    The main thing here is that parseInt parses the number with the operator. Code can be modified to the corresponding needs.

    0 讨论(0)
  • 2020-11-22 04:29

    I've recently done this in C# (no Eval() for us...) by evaluating the expression in Reverse Polish Notation (that's the easy bit). The hard part is actually parsing the string and turning it into Reverse Polish Notation. I used the Shunting Yard algorithm, as there's a great example on Wikipedia and pseudocode. I found it really simple to implement both and I'd recommend this if you haven't already found a solution or are looking for alternatives.

    0 讨论(0)
提交回复
热议问题