title: How to escape and unescape quotes in JavaScript?
body: <p>Here's a short piece of code:</p>
  
  <pre><code>var utility = {
      escapeQuotes: function(string) {
          return string.replace(new RegExp('"', 'g'),'\\"');
      },
      unescapeQuotes: function(string) {
          return string.replace(new RegExp('\\"', 'g'),'"');
      }
  };
  
  var a = 'hi "';
  
  var b = utility.escapeQuotes(a);
  var c = utility.unescapeQuotes(b);
  
  console.log(b + ' | ' + c);
  </code></pre>
  
  <p>I would expect this code to work, however as a result I receive:</p>
  
  <pre><code>hi \" | hi \"
  </code></pre>
  
  <p>If I change the first parameter of the new RegExp constructor in the unescapeQuotes method to 4 backslashes everything starts working as it should.</p>
  
  <pre><code>string.replace(new RegExp('\\\\"', 'g'),'"');
  </code></pre>
  
  <p>The result:</p>
  
  <pre><code>hi \" | hi " 
  </code></pre>
  
  <p><strong>Why are four backslashes needed as the first parameter of the new RegExp constructor? Why doesn't it work with only 2 of them?</strong></p>