Home >Web Front-end >JS Tutorial >How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?
Removing Hash Symbols from URLs with JavaScript
Removing the hash symbol (#) from a URL without refreshing the page requires a touch more finesse than simply setting window.location.hash to an empty string.
Elegant Solution for Modern Browsers
The modern HTML5 History API offers an elegant solution:
function removeHash() { history.pushState("", document.title, window.location.pathname + window.location.search); }
Example Demo:
https://jsfiddle.net/AndyE/ycmPt/
Wider Browser Support
For browsers lacking History API support, consider this gracefully degrading script:
function removeHash() { var scrollV = document.body.scrollTop; var scrollH = document.body.scrollLeft; var loc = window.location; if ("pushState" in history) { history.pushState("", document.title, loc.pathname + loc.search); } else { loc.hash = ""; document.body.scrollTop = scrollV; document.body.scrollLeft = scrollH; } }
Caveat
While this solution can remove the hash symbol, it's worth noting that it may not work in all browsers, particularly older versions.
Additional Note:
To replace the current page in the browser history, use replaceState() instead of pushState().
The above is the detailed content of How Can I Remove the Hash Symbol from a URL Using JavaScript Without Reloading the Page?. For more information, please follow other related articles on the PHP Chinese website!