Skip to content

Instantly share code, notes, and snippets.

@peterchappell
Forked from excalq/gist:2961415
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterchappell/aab8003708c1012fea0d to your computer and use it in GitHub Desktop.
Save peterchappell/aab8003708c1012fea0d to your computer and use it in GitHub Desktop.
JavaScript method for updating a url silently
// Explicitly save/update a url parameter using HTML5's replaceState().
function updateQueryStringParam (param, value) {
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
var urlQueryString = document.location.search;
var newParam = param + '=' + value;
var params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
var keyRegex = new RegExp('([\?&])' + param + '[^&]*');
// If param exists already, update it
if (urlQueryString.match(keyRegex) !== null) {
params = urlQueryString.replace(keyRegex, "$1" + newParam);
} else { // Otherwise, add it to end of query string
params = urlQueryString + '&' + newParam;
}
}
window.history.replaceState({}, "", baseUrl + params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment