title: Javascript Regexp loop all matches
body: <p>I'm trying to do something similar with stack overflow's rich text editor.  Given this text:</p>
  
  <pre><code>[Text Example][1]
  
  [1][http://www.example.com]
  </code></pre>
  
  <p>I want to loop each <code>[string][int]</code> that is found which I do this way:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var Text = "[Text Example][1]\n[1][http: //www.example.com]";
  // Find resource links
  var arrMatch = null;
  var rePattern = new RegExp(
    "\\[(.+?)\\]\\[([0-9]+)\\]",
    "gi"
  );
  while (arrMatch = rePattern.exec(Text)) {
    console.log("ok");
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>This works great, it alerts 'ok' for each <code>[string][int]</code>.  What I need to do though, is for each match found, replace the initial match with components of the second match.</p>
  
  <p>So in the loop $2 would represent the int part originally matched, and I would run this regexp (pseduo)</p>
  
  <pre><code>while (arrMatch = rePattern.exec(Text)) {
      var FindIndex = $2; // This would be 1 in our example
      new RegExp("\\[" + FindIndex + "\\]\\[(.+?)\\]", "g")
  
      // Replace original match now with hyperlink
  }
  </code></pre>
  
  <p>This would match</p>
  
  <pre><code>[1][http://www.example.com]
  </code></pre>
  
  <p>End result for first example would be:</p>
  
  <pre><code>&lt;a href="http://www.example.com" rel="nofollow"&gt;Text Example&lt;/a&gt;
  </code></pre>
  
  <h2>Edit</h2>
  
  <p>I've gotten as far as this now:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var Text = "[Text Example][1]\n[1][http: //www.example.com]";
  // Find resource links
  reg = new RegExp(
    "\\[(.+?)\\]\\[([0-9]+)\\]",
    "gi");
  var result;
  while ((result = reg.exec(Text)) !== null) {
    var LinkText = result[1];
    var Match = result[0];
    Text = Text.replace(new RegExp(Match, "g"), '&lt;a href="#"&gt;" + LinkText + "&lt;/a&gt;');
  }
  console.log(Text);</code></pre>
  </div>
  </div>
  </p>