Skip to content

Instantly share code, notes, and snippets.

@arnorhs
Created February 11, 2011 09:23
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 arnorhs/822122 to your computer and use it in GitHub Desktop.
Save arnorhs/822122 to your computer and use it in GitHub Desktop.
Javascript function to parse a query string
/*
This function is from my answer to a question on Stack Overflow
http://stackoverflow.com/questions/4963673/get-url-array-variables-in-javascript-jquery/4963817#4963817
*/
function getQueryString () {
var ret = {};
var parts = (document.location.toString().split('?')[1]).split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i].split('=');
// so strings will be correctly parsed:
p[1] = decodeURIComponent(p[1].replace(/\+/g, " "));
if (p[0].search(/\[\]/) >= 0) { // then it's an array
p[0] = p[0].replace('[]','');
if (typeof ret[p[0]] != 'object') ret[p[0]] = [];
ret[p[0]].push(p[1]);
} else {
ret[p[0]] = p[1];
}
}
return ret;
}
/*
But there are caveats. It will only work on a correctly formed
query string - there's no error detection. Also, it does not
work on numbered/indexed arrays.. that is when your array is
defined in the query string as:
?category[3]=1&category[4]=7&category[20]=3&id=8az
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment