title: How do I remove the global flag from a regular expression?
body: <p>Given a user (developer) provided regular expression, I need to remove the global flag if it exists, on Firefox 38 and above <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/global" rel="nofollow noreferrer">you can just set it</a>:</p>
  
  <pre><code>the_regex.global = false;
  </code></pre>
  
  <p>However that is not supported elsewhere.  So, I have created this pair of functions:</p>
  
  <pre><code>function deGlobal(regex) {
    if (!regex instanceof RegExp) return regex;
    if (!regex.global) return regex;
    var parts = regExpParts(regex);
    console.log(parts);
    if (parts) {
      return new RegExp(parts.pattern, parts.flags.replace("g", ""));
    } else {
      return false;
    }
  }
  
  function regExpParts(regex) {
    if (!regex instanceof RegExp) return false;
    var regex_string = regex.toString();
    var flags = regex_string.substring(regex_string.lastIndexOf('/') + 1);
    var pattern = regex_string.substring(1, regex_string.lastIndexOf('/'));
    return {
      flags: flags,
      pattern: pattern
    };
  }
  </code></pre>
  
  <p>Which for all of my test cases is doing great, but it seems like a very error prone method.</p>
  
  <p>Is there a case where these functions wouldn't work or there a better cross browser method of doing this?</p>
  
  <p><strong>FIDDLE:</strong> <a href="http://jsfiddle.net/trex005/324k2as5/" rel="nofollow noreferrer">http://jsfiddle.net/trex005/324k2as5/</a>.</p>