How to remove the hash from [removed] (URL) with J

2018-12-31 06:06发布

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.

13条回答
荒废的爱情
2楼-- · 2018-12-31 06:26

Solving this problem is much more within reach nowadays. The HTML5 History API allows us to manipulate the location bar to display any URL within the current domain.

function removeHash () { 
    history.pushState("", document.title, window.location.pathname
                                                       + window.location.search);
}

Working demo: http://jsfiddle.net/AndyE/ycmPt/show/

This works in Chrome 9, Firefox 4, Safari 5, Opera 11.50 and in IE 10. For unsupported browsers, you could always write a gracefully degrading script that makes use of it where available:

function removeHash () { 
    var scrollV, scrollH, loc = window.location;
    if ("pushState" in history)
        history.pushState("", document.title, loc.pathname + loc.search);
    else {
        // Prevent scrolling by storing the page's current scroll offset
        scrollV = document.body.scrollTop;
        scrollH = document.body.scrollLeft;

        loc.hash = "";

        // Restore the scroll offset, should be flicker free
        document.body.scrollTop = scrollV;
        document.body.scrollLeft = scrollH;
    }
}

So you can get rid of the hash symbol, just not in all browsers — yet.

Note: if you want to replace the current page in the browser history, use replaceState() instead of pushState().

查看更多
心情的温度
3楼-- · 2018-12-31 06:27

This will remove the trailing hash as well. eg: http://test.com/123#abc -> http://test.com/123

if(window.history.pushState) {
    window.history.pushState('', '/', window.location.pathname)
} else {
    window.location.hash = '';
}
查看更多
牵手、夕阳
4楼-- · 2018-12-31 06:30

You can replace hash with null

var urlWithoutHash = document.location.href.replace(location.hash , "" );
查看更多
还给你的自由
5楼-- · 2018-12-31 06:31

You can do it as below:

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

查看更多
刘海飞了
6楼-- · 2018-12-31 06:35

Try the following:

window.history.back(1);
查看更多
裙下三千臣
7楼-- · 2018-12-31 06:36

To remove the hash, you may try using this function

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);
    }
}
查看更多
登录 后发表回答