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

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从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>

把这个代码放在头部分

其他回答

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

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

要删除散列,可以尝试使用此函数

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}

我觉得这样更安全

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}

下面这个怎么样?

window.location。散列= ' '

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


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

window.location.hash='invalidtag'

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

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

您可以将哈希替换为null

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