Javascript Code Remove URL Search Query NO Reload

Javascript One Line Code Remove Search Query String Parameter from URL Without Reloading Page

Home Short:

In javascript there is the history object which stores your navigation in terms of pages you have visited. Using history.back() javascript command allows to go to the previous page in the history object and history.forward() javascript command allows us to go forward to the next page in the history object there will only be a page to go forward to in the history object if we have gone back first by clicking the back button in the web browser or running the javascript history.back() command.

To remove the url search query ie https://site.com?searchquery=somevalue without having to refresh or reload the page we simply call the window.history.replaceState which replaces the page current page in the history object with the url supplied in the 3rd argument of the window.history.replaceState(state, unused, url) javascript function.

For the purpose of removing the search query from the url of the current page, the url we pass as the 3rd argument in the javascript function window.history.replaceState(state, unused, url) will be window.location.origin + window.location.pathname which is the sites main url to the root or index page and the path, if any, to the current page which essentially removes both the search query and any hash in the url ie https://site.com?searchquery=somevalue#bottom

S
H
A
R
E