Evaluating a string as a mathematical expression in JavaScript

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

提交回复
热议问题