Last active
September 24, 2021 16:00
-
-
Save otakupahp/de193e83fdd3143ed01bb7769be1cf66 to your computer and use it in GitHub Desktop.
Work with query param from URL
This file contains hidden or 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
| /** 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