I have URL like: http://example.com#something, how do I remove #something, without causing the page to refresh?
I attempted the following solution:
window.location.hash = '';
However, this doesn't remove the hash symbol # from the URL.
I have URL like: http://example.com#something, how do I remove #something, without causing the page to refresh?
I attempted the following solution:
window.location.hash = '';
However, this doesn't remove the hash symbol # from the URL.
You can do it as below:
history.replaceState({}, document.title, window.location.href.split('#')[0]);
function removeLocationHash(){
var noHashURL = window.location.href.replace(/#.*$/, '');
window.history.replaceState('', document.title, noHashURL)
}
window.addEventListener("load", function(){
removeLocationHash();
});
I think, it would be more safe
if (window.history) {
window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
window.location.hash = '';
}
$(window).on('hashchange', function (e) {
history.replaceState('', document.title, e.oldURL);
});
Building off one of the answers given above, use this:
var scrollV, scrollH
var loc = window.location;
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
if ("pushState" in history) {
history.pushState("", document.title, loc.pathname + loc.search);
// Restore the scroll offset
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
} else {
loc.hash = "";
// Restore the scroll offset
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}