Saturday, 21 May 2011

Parsing the query string in Javascript into a single GLOBAL object


Two useful ideas combined:

1. From the book "Javascript the good bits", comes the idea to put all your (Javascript) global variables as ?? of a single global object called GLOBAL like this

var GLOBAL={}
GLOBAL.v1="value1";
GLOBAL.v2=0xFF;

2. If the html document is called with a URL with a search string (file.htm?v1=value1&v2=0xFF) then using Javascript you can parse the query string in the following way...

// http://stevenbenner.com/2010/03/javascript-regex-trick-parse-a-query-string-into-an-object/
// load GLOBAL with properties from the querystring at the end of the URL
// e.g. "?session=2010_2011&mod_id=COA122" produces GLOBAL.session='2010_2011' & GLOBAL.mod_id='COA122'

var GLOBAL={}

location.search.replace(
  new RegExp("([^?=&]+)(=([^&]*))?", "g"),
  function($0, $1, $2, $3) {
    var e="GLOBAL."+$1+" = '"+$3+"'"; 
    //alert(e); 
    eval(e);
  }
);

No comments:

Post a Comment