title: Parse JSON-like input containing /regexp/ literals
body: <p>In my web app, I would like to accept arbitrary JavaScript objects as GET parameters. So I need to parse <code>location.search</code> in a way similar to <code>eval</code>, but I want to create <strong>self-contained objects only</strong> (object literals, arrays, regexps and possibly restricted-access functions):</p>
  
  <pre class="lang-js prettyprint-override"><code>var search =
      location.search ?
      decodeURIComponent(location.search).substring(1).split('&amp;') :
      ['boo=alert(1)', 'filter={a: /^t/, b: function(i){return i+1;}}']
  ;
  var params = {};
  for (var i = 0, temp; i &lt; search.length; i++){
      temp = search[i].split('=');
      temp = temp[1] ? temp : [temp[0], null];
      params[temp[0]] = saferEval(temp[1]);
  };
  console.log(params);
  </code></pre>
  
  <p>I came up with a version of <code>saferEval</code> function that blocks access to global variables, but it does not block access to built-in functions like <code>alert()</code>:</p>
  
  <pre class="lang-js prettyprint-override"><code>var saferEval = function(s) {
      'use strict';
      var deteleGlobals =
          'var ' +
          Object.getOwnPropertyNames(window)
            .join(',')
            .replace(/(?:eval|chrome:[^,]*),/g, '') +
          ';'
      ;
      try {
          return eval(deteleGlobals + '(' + s + ');') || s;
      } catch(e) {
          return s;
      };
  };
  </code></pre>
  
  <p>See my <strong><a href="http://jsfiddle.net/deathApril/P7x2u/1/" rel="nofollow">jsFiddle</a></strong> - <code>alert(1)</code> code is executed.
  <sup>Note that <code>top.location</code> is not accessible to jsFiddle scripts, you have to run the code locally if you want to fiddle with actual query parameters like <code>?filter={a: /%5Cd+/g}</code>.</sup></p>
  
  <p>I would <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval#Parsing_JSON_%28converting_strings_to_JavaScript_objects%29" rel="nofollow">use JSON</a>, but I need to have regular expressions at arbitrary places inside arrays and objects. I do not send any of these object back to the server, so using <code>eval</code> for this shouldn't harm the security so much...</p>
  
  <p><strong>How can I convert a string</strong> (that encodes JavaScript object) <strong>into object without giving it access to global namespace and built-in functions?</strong></p>
  
  <p><em>UPDATE - only useful "arbitrary" objects turned out to be regexp literals...</em></p>