Skip to content

Instantly share code, notes, and snippets.

@monostere0
Last active February 19, 2020 08:11
Show Gist options
  • Save monostere0/f611c8e6c7792cd29ff9 to your computer and use it in GitHub Desktop.
Save monostere0/f611c8e6c7792cd29ff9 to your computer and use it in GitHub Desktop.
Retrieve the query string params as JS object
Object.defineProperty(location, 'searchJSON', {
get: function() {
var a = window.location,
b = a.href.split('?'),
c = a.search;
return (c.slice(1) || (b.length > 1 && b[1]) || '').split("&").reduce(function(p, c) {
return (c = c.split("=")) && (p[c[0]] = unescape(c[1])) && p
}, {}) || {};
},
enumerable: false,
configurable: false
});
//usage:
// window.location.searchJSON will retrieve an object containing the query string in JSON format
// http://test.com?hello=world&foo=bar will translate to { 'hello': 'world', 'foo': 'bar' }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment