title: Replacing the nth instance of a regex match in Javascript
body: <p>I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances.  For example, I have this string:</p>
  
  <pre><code>12||34||56
  </code></pre>
  
  <p>I want to replace the second set of pipes with ampersands to get this string:</p>
  
  <pre><code>12||34&amp;&amp;56
  </code></pre>
  
  <p>The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:</p>
  
  <pre><code>23||45||45||56||67 -&gt; 23&amp;&amp;45||45||56||67
  
  23||34||98||87 -&gt; 23||34||98&amp;&amp;87
  </code></pre>
  
  <p>I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on <code>/\|\|/</code> and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this.  Note that this would be for Javascript, so it's possible to generate a regex at runtime using <code>eval()</code>, but it's not possible to use any Perl-specific regex instructions.</p>