title: Best way to get string representation of regex from regex literal
body: <p>If I do this:</p>
  
  <pre><code>// note that \x1f is a control character
  var regex = new RegExp("\x1f");
  
  // prints "//"
  console.log(regex.toString()); 
  </code></pre>
  
  <p>If I instead do this:</p>
  
  <pre><code>var regex = /\\x1f/;
  
  // prints "/\\x1f/"
  console.log(regex.toString());
  </code></pre>
  
  <p>I'd like to be able to get the first result (<code>//</code> - a string with a control character) from the second regular expression.  Is there a simple way to do this?  So far, I've only been able to do this with a disgusting <code>eval</code> hack:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var regexValue = /\\x1f/.toString();
  
  let escapedLiteral = regexValue
  
      // turn double backslashes (\\) into single backslashes (\), 
      .replace(/\\\\/g, '\\')
      
      // remove the opening and closing forward slashes (/).
      // this needs to be more intelligent - what if there are flags?
      .slice(1, -1);
  
  // there could be an invalid regular expression string
  try {
    regexValue = eval('new RegExp("' + escapedLiteral + '")').toString();
  } catch (e) {
    regexValue = null;
  }
  
  // should print "//"
  document.writeln(regexValue);</code></pre>
  </div>
  </div>
  </p>
  
  <p>I'm doing some JavaScript source code parsing and this difference is making things challenging.</p>