Last active
July 5, 2023 16:57
-
-
Save Juandresyn/34fe1164dcebf70472f0275d08a887af to your computer and use it in GitHub Desktop.
Get query params
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
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