title: RegEx Replacement in JavaScript
body: <p>I have a piece of code which replaces tokens in a string. I have the replacement values stored in an array.</p>
  
  <p>Essentially, I would like to analyse the string and replace it by array key. For example, I want to replace any instance of <code>[my_forename]</code> with <code>replacements['my_forname']</code>. The keys in the array are identical to whatever is between the squared brackets in the string.</p>
  
  <p>A more comprehensive view:</p>
  
  <pre><code>replacements['my_forename'] = 'Ben';
  replacements['my_surname']  = 'Major';
  replacements['my_verbose_name'] = 'Ben Major';
  
  // The following is the input string:
  // 'My name is [my_forename] [my_surname], or [my_verbose_name].';
  // And it should output:
  // 'My name is Ben Major, or Ben Major.';
  </code></pre>
  
  <p>If anyone can offer a RegEx that will handle the replacement, I would be grateful. It is possible that there will be more than one instance of the same token, but I have handled that using the following <code>replaceAll</code> function:</p>
  
  <pre><code>String.prototype.replaceAll = function(needle, replacement)
  {
      return this.replace(new RegExp(needle, 'g'), replacement);
  }
  </code></pre>
  
  <p>This causes a max stack limit though, because creating a <code>RegExp</code> object from anything containing <code>[]</code> causes issues.</p>
  
  <p>Any help would be gratefully received!</p>