Skip to content

Instantly share code, notes, and snippets.

@jerryasher
Created January 25, 2016 02:08
Show Gist options
  • Save jerryasher/18ff0822f8d511d30516 to your computer and use it in GitHub Desktop.
Save jerryasher/18ff0822f8d511d30516 to your computer and use it in GitHub Desktop.
Snippet to parse URL query strings, returning an object whose keys are parameter names and whose values are an array of the parameters themselves
// via http://codereview.stackexchange.com/questions/9574/faster-and-cleaner-way-to-parse-parameters-from-url-in-javascript-jquery
function parseQueryString() {
var query = (window.location.search || '?').substr(1),
map = {};
query.replace(/([^&=]+)=?([^&]*)(?:&+|$)/g, function(match, key, value) {
(map[key] = map[key] || []).push(value);
});
return map;
}
// Note that I'm not returning exactly the same data structure you are, but that's on purpose. Mashing an object and array together will fail if the query string has keys like "length" or "push".
// This function will also work with parameters that are re-used, parameters with empty values, parameters without an equals sign, and malformed urls. If you know you won't need to parse query strings where the same key is used multiple times, you could replace line 5 with map[key] = value;.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment