title: Extract Variables, Coeffcients & Powers from a Polynomial string (Javascript)
body: <p>I am trying to extract different parts of a polynomial string like variables, coefficients and powers from a string in javascript. So far I am able to extract these from a simple polynomial string e.g. "-13x^2+2-12x^4".</p>
  
  <p>I want to extend this to extract from a relatively complex polynomial string. Something like "-13x^2y^3+2-12x^-4".</p>
  
  <p>Here is the code that I have:</p>
  
  <pre><code>function extractPolynomial(polynomialStr) {
      var arr = [];
      polynomialStr = polynomialStr.match(/[+-]?\d+(x|y)(\^\d)*|[+-\s]\d+/g);
      polynomialStr.forEach(function (match) {
          var vals = match.split('^');
          var coeff = parseInt(vals[0]);
          var variable = vals[0].match(/[a-z]/gi) ? vals[0].match(/[a-z]/gi)[0] : "";
          var power = 1;
          if(vals.length &gt; 1){
              power = parseInt(vals[1]);
          }
          else {
              if (variable === "") {
                  power = 0;
              }
              else {
                  power = 1;
              }
          }
          arr.push({
              coeff: coeff,
              variable: variable,
              power: power
          })
      });
      return arr;
  }
  </code></pre>
  
  <p>Here is the fiddle: <a href="https://jsfiddle.net/889ruq7a/" rel="nofollow noreferrer">https://jsfiddle.net/889ruq7a/</a></p>