Skip to content

Instantly share code, notes, and snippets.

@excalq
Last active March 19, 2024 17:45
Show Gist options
  • Save excalq/2961415 to your computer and use it in GitHub Desktop.
Save excalq/2961415 to your computer and use it in GitHub Desktop.
Javacript: Set or Update a URL/QueryString Parameter, and update URL using HTML history.replaceState()
// 2024 Update, use URLSearchParams [https://caniuse.com/urlsearchparams]
export function createQueryString2(name: string, value: string, searchParams: any) {
const params = new URLSearchParams(searchParams);
params.set(name, value.toLowerCase());
return params.toString();
}
// ---- Original 2012 version, when browsers really sucked ----
// 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);
}
@excalq
Copy link
Author

excalq commented Mar 19, 2024

Thanks @mbuguaMaina, URLSearchParams is definitely the best modern approach. I've updated the original Gist to use your version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment