You can extract the key/value pairs from the location.search property, this property has the part of the URL that follows the ?
symbol, including the ?
symbol.
function queryObj() {
var result = {}, queryString = location.search.slice(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// Usage:
var myParam = queryObj()["myParam"];
Update:
No need to use regex:
function queryObj() {
var result = {}, keyValuePairs = location.search.slice(1).split('&');
keyValuePairs.forEach(function(keyValuePair) {
keyValuePair = keyValuePair.split('=');
result[keyValuePair[0]] = keyValuePair[1] || '';
});
return result;
}
For IE8- support include this tiny Array.forEach
* polyfill:
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
From: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
*Array.forEach
aka the better for loop