Skip to content

Instantly share code, notes, and snippets.

@oobleck
Created January 23, 2014 06:45
Show Gist options
  • Save oobleck/8574023 to your computer and use it in GitHub Desktop.
Save oobleck/8574023 to your computer and use it in GitHub Desktop.
URL Query parameter helpers: 1. on-demand access function `getParam` 2. onpopstate object creation of `window.location.params`
// Inspired by http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript
;(function() {
'use strict';
// On-demand retreival of query params
window.getParam = function getParam(name) {
var rxName = new RegExp('[\\?&]'+name+'[=]([^&#]*)');
var check = rxName.exec(window.location.search);
return (check === null) ? check : decodeURIComponent(check[1].replace(/\+/g, ' '));
};
// Run-once params object setup (on history change)
// window.location.params
;(window.onpopstate = function() {
var rxParams = /([^\?&=]+)=?([^&#]*)/g;
var decode = function decode(s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
var match;
window.location.params = {};
while (match = rxParams.exec(window.location.search)) {
window.location.params[decode(match[1])] = decode(match[2]);
}
}());
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment