Skip to content

Instantly share code, notes, and snippets.

@andyexeter
Created October 10, 2017 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andyexeter/e8446cc0b7773d0198b2d64fe5a08456 to your computer and use it in GitHub Desktop.
Save andyexeter/e8446cc0b7773d0198b2d64fe5a08456 to your computer and use it in GitHub Desktop.
JavaScript function to return a query string as an object
function getQuery(query) {
query = query || window.location.search;
var queryString = {};
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
pair[0] = decodeURIComponent(pair[0]);
pair[1] = decodeURIComponent(pair[1]);
// If first entry with this name
if (typeof queryString[pair[0]] === 'undefined') {
queryString[pair[0]] = pair[1];
// If second entry with this name
} else if (typeof queryString[pair[0]] === 'string') {
queryString[pair[0]] = [queryString[pair[0]], pair[1]];
// If third or later entry with this name
} else {
queryString[pair[0]].push(pair[1]);
}
}
return queryString;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment