Skip to content

Instantly share code, notes, and snippets.

@Juandresyn
Last active July 5, 2023 16:57
Show Gist options
  • Save Juandresyn/34fe1164dcebf70472f0275d08a887af to your computer and use it in GitHub Desktop.
Save Juandresyn/34fe1164dcebf70472f0275d08a887af to your computer and use it in GitHub Desktop.
Get query params
const getUrlParameter = (name) => {
const nameClean = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
const regex = new RegExp('[\\?&]' + nameClean + '=([^&#]*)');
const results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
const removeUrlParameter = (url, paramKey) => {
const r = new URL(url);
r.searchParams.delete(paramKey);
history.replaceState(null, '', r.href);
}
const addUrlParameter = (param, value) => {
const urlParams = new URLSearchParams(window.location.search);
urlParams.set(param, value);
window.location.search = urlParams;
}
const editUrlParameter = (param, value) => {
if (getUrlParameter(param)) {
removeUrlParameter(param)
}
addUrlParameter(param, value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment