Created
January 25, 2016 02:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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