-
-
Save sbtnh/ae2db27487eaa22ad947e862429cd562 to your computer and use it in GitHub Desktop.
Javacript: Set or Update a URL/QueryString Parameter, and update URL using HTML history.replaceState()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Explicitly save/update a url parameter using HTML5's replaceState(). | |
function updateQueryStringParam(key, value) { | |
const baseUrl = [location.protocol, '//', location.host, location.pathname].join(''); | |
const urlQueryString = document.location.search; | |
let newParam = key + '=' + value; | |
let params = '?' + newParam; | |
// If the "search" string exists, then build params from it | |
if (urlQueryString) { | |
const 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