-
-
Save tectiv3/381580c911d7950e0d0dc9665dc27928 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 hidden or 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(). | |
var updateQueryStringParam = function (key, value) { | |
var baseUrl = [location.protocol, '//', location.host, location.pathname].join(''), | |
urlQueryString = document.location.search, | |
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 value is undefined - unset it | |
var match = urlQueryString.match(keyRegex); | |
if (match !== null) { | |
params = urlQueryString.replace(keyRegex, value == undefined ? (match[1] == '?' ? '?' : ''): "$1" + newParam); | |
} else { // Otherwise, add it to end of query string | |
params = urlQueryString + (value != undefined ? '&' + newParam : ''); | |
} | |
} | |
params = params.replace('?&', '?'); | |
window.history.replaceState({}, "", baseUrl + params); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment