我有URL: http://example.com#something,我如何删除#一些,而不导致页面刷新?

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从URL中删除散列符号#。


当前回答

function removeLocationHash(){
    var noHashURL = window.location.href.replace(/#.*$/, '');
    window.history.replaceState('', document.title, noHashURL) 
}

window.addEventListener("load", function(){
    removeLocationHash();
});

其他回答

$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});

下面是另一个使用href更改位置并在不滚动的情况下清除散列的解决方案。

这里解释了神奇的解决方案。规格。

const hash = window.location.hash;
history.scrollRestoration = 'manual';
window.location.href = hash;    
history.pushState('', document.title, window.location.pathname);

注意:提议的API现在是WhatWG HTML生活标准的一部分

(太多的答案是多余的和过时的。)现在最好的解决方案是:

history.replaceState(null, null, ' ');
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);

您可以将哈希替换为null

var urlWithoutHash = document.location.href.replace(location.hash , "" );