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

我尝试了以下解决方案:

window.location.hash = '';

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


当前回答

你可以这样做:

history.replaceState({}, document.title, window.location.href.split('#')[0]);

其他回答

简单优雅:

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

我觉得这样更安全

if (window.history) {
    window.history.pushState('', document.title, window.location.href.replace(window.location.hash, ''));
} else {
    window.location.hash = '';
}
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);

根据上面给出的答案之一,用这个:

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;
}
$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});