Skip to content

Instantly share code, notes, and snippets.

@otakupahp
Last active September 24, 2021 16:00
Show Gist options
  • Save otakupahp/de193e83fdd3143ed01bb7769be1cf66 to your computer and use it in GitHub Desktop.
Save otakupahp/de193e83fdd3143ed01bb7769be1cf66 to your computer and use it in GitHub Desktop.
Work with query param from URL
/** Get a value from the Query params */
function otkGetQueryParam(name, url = window.location.href) {
let objectURL = new URL( url );
let searchParams = new URLSearchParams( objectURL.search );
return searchParams.get(name);
}
/** Set a value to the Query params */
function otkSetQueryParam(name, url = window.location) {
const urlObj = new URL(url);
urlObj.searchParams.set( name, 1 );
history.replaceState( null, '', urlObj.href );
}
/** Remove a value from the Query params */
function otkDeleteQueryParam(name, url = window.location, replaceLocation = true) {
const urlObj = new URL(url);
urlObj.searchParams.delete( name );
if( replaceLocation ) {
history.replaceState( null, '', urlObj.href );
}
else {
return urlObj.href;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment