JSFiddle - React, Tailwind, and code Playground

by Samir Chaves

HTML

<p>(9.7 ^ 7) ^90</p>










<h4></h4>

JavaScript

var string = $("p").html();

    function captureBefore(string) {
      var result;
      var n = string.indexOf("^");
      var i = n - 1;
      while (!(string.charAt(i) != " ")) {
        --i;
      }
      if (!(/\d/.test(string.charAt(i)))) {
        var nOpen = 1;
        var nClose = 0;
        while (nOpen != nClose) {
          if (string.charAt(i - 1) == ")") {
            ++nOpen;
          } else if (string.charAt(i - 1) == "(") {
            ++nClose;
          }
          i -= 1;
        }
        if (/[a-z]/.test(string.charAt(i - 1))) {
          while ((/[a-zA-Z.]/.test(string.charAt(i - 1)))) {
            i -= 1;
          }
        }
        result = string.substring(i, n);
      } else {
        while (/\d/.test(string.charAt(i)) || /[-|+|.]/.test(string.charAt(i))) {
          i -= 1;
        }
        result = string.substring(i + 1, n);
      }
      return result;
    }

    function captureAfter(string) {
      var result;
      var n = string.indexOf("^");
      var i = n + 1;
      while (string.charAt(i) == " " || /[a-zA-Z.]/.test(string.charAt(i))) {
        ++i;
      }
      if (/[-|+]/.test(string.charAt(i))) {
        ++i;
      }
      if (!(/(\d)/.test(string.charAt(i)))) {
        var nOpen = 1;
        var nClose = 0;
        while (nOpen != nClose) {
          if (string.charAt(i + 1) == "(") {
            ++nOpen;
          } else if (string.charAt(i + 1) == ")") {
            ++nClose;
          }
          i += 1;
        }
        result = (string.substring(n + 1, i + 1));
      } else {
        while (/\d/.test(string.charAt(i)) || /[-|+|.]/.test(string.charAt(i))) {
          i += 1;
        }
        result = (string.substring(n + 1, i));
      }
      return result;
    }

    if (/\^/g.test(string)) {
      string = string.replace(/\s*\^\s*/g, "^")
      while (/\^/g.test(string)) {
        string = string.replace(captureBefore(string) + "^" + captureAfter(string), "Math.pow(" + captureBefore(string) + ", " +...