If you're using jQuery, you can use a library, such as [jQuery BBQ: Back Button & Query Library][1].
> ...jQuery BBQ provides a full `.deparam()` method, along with both hash state management, and fragment / query string parse and merge utility methods.
Edit: Adding Deparam Example:
<!-- begin snippet: js hide: false -->
<!-- language: lang-js -->
var DeparamExample = function() {
var params = $.deparam.querystring();
//nameofparam is the name of a param from url
//code below will get param if ajax refresh with hash
if (typeof params.nameofparam == 'undefined') {
params = jQuery.deparam.fragment(window.location.href);
}
if (typeof params.q != 'undefined') {
var paramValue = params.nameofparam.toString();
}
};
<!-- end snippet -->
If you want to just use plain JavaScript, you could use...
<!-- language: lang-js -->
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
Because of the new HTML History API and specifically `history.pushState()` and `history.replaceState()`, the URL can change which will invalidate the cache of parameters and their values.
This version will update its internal cache of parameters each time the history changes.
[1]: http://benalman.com/projects/jquery-bbq-plugin/