How do you write an arithmetic expression parser in JavaScript, without using eval or a constructor function?

后端 未结 4 2103
无人及你
无人及你 2020-12-09 21:47

Given a string:

 var str1 = \"25*5+5*7\";

Without using eval or the constructor function in JavaScript, how would I be able to

4条回答
  •  独厮守ぢ
    2020-12-09 22:22

    You can create a new script:

    function parse(str) {
      var s = document.createElement('script');
      s.text = "window.result = " + str;
      document.body.appendChild(s); // Run script
      document.body.removeChild(s); // Clean up
      return result;                // Return the result
    }
    document.body.innerHTML = parse("5*5+5*5");

    Or use event handler content attributes:

    function parse(str) {
      var el = document.createElement('div');
      el.setAttribute('onclick', "this.result = " + str);
      el.onclick();     // Run script
      return el.result; // Return the result
    }
    document.body.innerHTML = parse("5*5+5*5");

    Note these approaches are unsafe and as evil as eval but uglier. So I don't recommend them.

提交回复
热议问题