Created
January 6, 2022 11:18
-
-
Save semihkeskindev/d0681b4d22d3e9ac53f71a2a2d8d6c05 to your computer and use it in GitHub Desktop.
update query string parameters without page refresh in javascript
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
function updateQueryStringParam(key, value) { | |
let 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) { | |
let updateRegex = new RegExp('([\?&])' + key + '[^&]*'); | |
let removeRegex = new RegExp('([\?&])' + key + '=[^&;]+[&;]?'); | |
if (typeof value == 'undefined' || value == null || value == '') { // Remove param if value is empty | |
params = urlQueryString.replace(removeRegex, "$1"); | |
params = params.replace(/[&;]$/, ""); | |
} else if (urlQueryString.match(updateRegex) !== null) { // If param exists already, update it | |
params = urlQueryString.replace(updateRegex, "$1" + newParam); | |
} else { // Otherwise, add it to end of query string | |
params = urlQueryString + '&' + newParam; | |
} | |
} | |
// no parameter was set so we don't need the question mark | |
params = params == '?' ? '' : params; | |
window.history.replaceState({}, "", baseUrl + params); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment