Skip to content

Instantly share code, notes, and snippets.

@BastinRobin
Forked from excalq/gist:2961415
Created September 28, 2016 16:23
Show Gist options
  • Save BastinRobin/0cca0e267408e361062a8681d0cc556d to your computer and use it in GitHub Desktop.
Save BastinRobin/0cca0e267408e361062a8681d0cc556d to your computer and use it in GitHub Desktop.
Javacript: Set or Update a URL/QueryString Parameter, and update URL using HTML history.replaceState()
// Explicitly save/update a url parameter using HTML5's replaceState().
function updateQueryStringParam(param, value) {
baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
urlQueryString = document.location.search;
var newParam = key + '=' + value,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (urlQueryString) {
keyRegex = new RegExp('([\?&])' + key + '[^&]*');
// 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