Evaluating a string as a mathematical expression in JavaScript

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

    Simple and elegant with Function()

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

提交回复
热议问题