title: Is this use of Javascript eval() 100% safe?
body: <p>I'm writing a PHP library which generates Javascript code.</p>
  
  <p>The Javascript code has a number of components named <code>component001</code>, <code>component002</code>, etc.</p>
  
  <p>Pages are loaded dynamically via AJAX.</p>
  
  <p>I need to pass the name of the component via URL variable which is then evaled() by the script.</p>
  
  <p>The only way I am protecting what is being evaled is with the regular expression <code>^component[0-9]{3}$</code>: if it passes it gets evaled, otherwise it does not.</p>
  
  <p><strong>To me this is 100% safe since nothing will get executed unless it is simply the name of one of my known components, or is there something about the <code>eval()</code> command that could be exploited in this code sample, e.g. regex injection, some kind of cross site scripting etc.?</strong></p>
  
  <pre><code>window.onload = function() {
  
      // *** DEFINED IN ANOTHER JAVASCRIPT FILE:
      var component001 = 'testing111';
      var component002 = 'testing222';
      var component003 = 'testing333';
  
      var APP = {};
  
      APP.getUrlVars = function() {
          var vars = [], hash;
          var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;');
          for(var i = 0; i &lt; hashes.length; i++) {
              hash = hashes[i].split('=');
              vars.push(hash[0]);
              vars[hash[0]] = hash[1];
          }
          return vars;
      }
  
      APP.getUrlVar = function(name, defaultValue) {
          defaultValue = (typeof defaultValue == 'undefined') ? '' : defaultValue;
          var vars = APP.getUrlVars();
          if(vars[name] === undefined)
          {
              return defaultValue;
          } else {
              return vars[name];
          }
      }
  
      APP.safeEval = function(nameOfComponent) {
          var REGEX_VALID_NAME = /^component[0-9]{3}$/;
          if(REGEX_VALID_NAME.test(nameOfComponent)) {
              return eval(nameOfComponent);
          } else {
              return 'ERROR';
          }
  
      }
  
      // *** JAVASCRIPT FILE LOADED VIA AJAX:
  
      var nameOfComponentToDisplay = APP.getUrlVar('compname', 'component001');
      var component = APP.safeEval(nameOfComponentToDisplay);
      document.write(component);
  
  }
  </code></pre>