Skip to content

Instantly share code, notes, and snippets.

@semihkeskindev
Created January 6, 2022 11:18
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 semihkeskindev/d0681b4d22d3e9ac53f71a2a2d8d6c05 to your computer and use it in GitHub Desktop.
Save semihkeskindev/d0681b4d22d3e9ac53f71a2a2d8d6c05 to your computer and use it in GitHub Desktop.
update query string parameters without page refresh in javascript
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