random memes }

Reading parameters from URL - Javascript

Another simple, minimal Javascript snippet - how to read URL parameters.

var PARAMETERS = {}; PARAMETERS.load = function() { PARAMETERS.map = {}; window.location.search.substring(1).replace(/([^&=]+)(=)?(&|$)/g,function(s,k,q,v){ if (undefined === PARAMETERS.map[k]) { PARAMETERS.map[k] = []; } PARAMETERS.map[k].push(decodeURIComponent(v)); }); for (var k in PARAMETERS.map) { var a = PARAMETERS.map[k]; PARAMETERS.map[k] = ((1 == a.length) ? a[0] : a); } }; PARAMETERS.load();

That's all. Value for the parameter "who" is found at PARAMETERS.map.who already decoded. Repeated parameters are turned into an array, i.e.: "?a=1&a=2&a=3" becomes [1,2,3].

Try it out on the test page. Code can be found in base.js.