Skip to content

Instantly share code, notes, and snippets.

@SneakyBrian
Created October 5, 2012 17:17
Show Gist options
  • Save SneakyBrian/3841097 to your computer and use it in GitHub Desktop.
Save SneakyBrian/3841097 to your computer and use it in GitHub Desktop.
Get Query String for current page as object
(function (window) {
//declare the variables here,
//as js variable hoisting will do this
//here anyway
var m, queryString, re;
//if the window query object does not exist
if (!window.query) {
//create it
window.query = {};
//get the query string (without the #)
queryString = location.search.substring(1);
//declare the regex
re = /([^&=]+)=([^&]*)/g
//execute the regex for each query parameter
while (m = re.exec(queryString)) {
//add the query parameter to the query object
window.query[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
}
}(window));
@sindresorhus
Copy link

Using regex for this is just wrong and will fail in some scenarios.

You'd better off using a tiny reusable module like:
https://github.com/sindresorhus/query-string

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment