title: JavaScript Regular Expression with character class quantifier variable
body: <p>I am trying to create a regular expression with a character class that has a specific quantifier which is a variable for example:</p>
  
  <pre><code>var str = "1234.00";
  var quantifier = 3;
  str = str.replace(/(\d)(\d{quantifier}\.)/,"$1,$2");
  //str should be "1,234.00"
  </code></pre>
  
  <p>This works as follows (without a variable):</p>
  
  <pre><code>var str = "1234.00";
  str = str.replace(/(\d)(\d{3}\.)/,"$1,$2");
  //str == "1,234.00"
  </code></pre>
  
  <p>However it does not have the same functionality with a <a href="https://stackoverflow.com/questions/1695633/how-to-pass-a-variable-into-regex-in-jquery-javascript">quoted pattern instead of a slash-delimited pattern</a> as follows:</p>
  
  <pre><code>var str = "1234.00";
  str = str.replace("(\d)(\d{3}\.)","$1,$2");
  //str == "1234.00" - not "1,234.00"
  //quote symbol choice does not change this
  str = str.replace('(\d)(\d{3}\.)',"$1,$2");
  //str == "1234.00" - not "1,234.00"
  </code></pre>
  
  <p>edit: to be more clear I have added a summary question which was answered below:
  <strong>How do I create a regular expression with an interpolated variable from a quoted string?</strong></p>
  
  <p>Although my preference would be to use interpolation, it seems that is not available (at least in this context), and is not necessary.</p>
  
  <p>I have also tried to come up with a way to <a href="https://stackoverflow.com/questions/185510/how-can-i-concatenate-regex-literals-in-javascript">concatenate/join some regex literals</a> to achieve the same result, but have been unable to do so for this use case.</p>
  
  <p>As a side note - I am familiar with this type of regular expression in perl:</p>
  
  <pre><code>my $str = "1234.00";
  my $quantifier = 3;
  $str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
  # $str eq "1,234.00"
  </code></pre>
  
  <p>Which can be made useful as follows:</p>
  
  <pre><code>my $str = "1234567890.00";
  for my $quantifier (qw(9 6 3)) {
      $str =~ s/(\d)(\d{$quantifier}\.)/$1,$2/;
  }
  # $str eq "1,234,567,890.00"
  </code></pre>
  
  <p><strong>With the suggestions/answers provided I have created a sample currency string prototype as follows:</strong></p>
  
  <pre><code>String.prototype.toCurrency = function() {
      var copy = parseFloat(this).toFixed(2);
      for (var times = parseInt(copy.length/3); times &gt; 0; times--) {
          var digits = times * 3;
          var re = new RegExp("(\\d)(\\d{" + digits + "}\\.)");
          copy = copy.replace(re,"$1,$2");
      }
      return '$'+copy;
  };
  str = "1234567890";
  str.toCurrency();
  // returns "$1,234,567,890.00"
  </code></pre>