title: Using the anonymous function in String.replace() method
body: <p>I have an array of regular expressions, at the moment just one element in length, and a string which I want to search/replace by looping through the array:</p>
  
  <pre><code>var str = "i am*happy all the*time",
      rex = [
          /(\S)\s*\*\s*(\S)/g
          ],
      i = 0,
      r = rex.length;
  </code></pre>
  
  <p>This is how I'm trying to achieve this at the moment:</p>
  
  <pre><code>for (i; i &lt; r; i += 1) {
      str.replace(rex[i], function(star, p1, p2) {
          console.log(i, star, p1, p2);
          return p1 + '\\s*(.*)\\s*' + p2;
      });
  }
  </code></pre>
  
  <p>The result should be <code>i am*\\s*(.*)\\s*happy all the\\s*(.*)\\s*time</code>. But at the moment, <code>str</code> seems unaffected, even though when I check the console the relevant matches are being made. You can see this for yourself <a href="http://jsfiddle.net/Y3czg/5/" rel="nofollow">here</a>.</p>
  
  <p>So am I missing something simple, have I misunderstood something about using lambda expressions in String.replace(), or is there something more fundamentally wrong here?</p>
  
  <p>...</p>
  
  <p><em><strong>EXTRA INFO:</em></strong>
  I'm using Chrome 24 right now, in case that's of interest; I had read a while ago that anonymous functions in String.replace() weren't available to all browsers though I assumed that would be resolved by now (the option was introduced in ECMAScript v3).</p>