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

我尝试了以下解决方案:

window.location.hash = '';

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


当前回答

下面这个怎么样?

window.location。散列= ' '

请注意,我设置哈希到一个单一的空间,而不是一个空字符串。


将散列设置为无效锚也不会导致刷新。例如,

window.location.hash='invalidtag'

但是,我发现上面的解决方案是误导性的。这似乎表明在给定位置上有一个具有给定名称的锚,尽管没有锚。同时,使用空字符串会导致页面移到顶部,这有时是不可接受的。使用空格还可以确保当URL被复制、收藏和再次访问时,页面通常会位于顶部,空格将被忽略。

这是我在StackOverflow上的第一个答案。希望有人觉得它有用,它符合社区标准。

其他回答

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

history.replaceState(null, null, ' ');

你可以这样做:

history.replaceState({}, document.title, window.location.href.split('#')[0]);
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
<script type="text/javascript">
var uri = window.location.toString();
if (uri.indexOf("?") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    window.history.replaceState({}, document.title, clean_uri);
}
</script>

把这个代码放在头部分

简单优雅:

history.replaceState({}, document.title, ".");  // replace / with . to keep url