Friday, October 5, 2012

Javascript - Get Query String for current page as object

Here is a code snippet that gets the current query string parameters and puts them into a query object that can then be used to read the values in subsequent code.
(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));
view raw window.query.js hosted with ❤ by GitHub

No comments:

Post a Comment