Skip to content

Instantly share code, notes, and snippets.

@dvdrtrgn
Created February 16, 2012 18:43
Show Gist options
  • Save dvdrtrgn/1846962 to your computer and use it in GitHub Desktop.
Save dvdrtrgn/1846962 to your computer and use it in GitHub Desktop.
extend Location to read or write a search string
location.parse = function () { //_qp_//
var i, e, arr, str = location.search,
out = new(function Queries() {});
if (!str || str.charAt(0) !== '?') {
return {};
}
arr = decodeURI(str.substr(1)).split('&'); // no '?'
for (i = 0; i < arr.length; i++) {
e = arr[i].split('=');
out[e[0]] = e[1] ? decodeURIComponent(e[1]) : null;
}
this.params = out; // stor'em
return out;
};
location.query = function (obj, go) { //_pq_//
var i, e, arr = [], str = '';
if (typeof obj !== 'object') {
return false;
}
for (i in obj) {
e = obj[i];
if (e === null || e === undefined || e === '') {
arr.push(i);
} else {
arr.push(i + '=' + encodeURIComponent(e));
}
}
str = encodeURI(arr.join('&'));
if (go || go === undefined) location.search = str;
return str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment