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:36

Here is another solution to change the location using href and clear the hash without scrolling.

The magic solution is explained here. Specs here.

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

NOTE: The proposed API is now part of WhatWG HTML Living Standard

查看更多
后来的你喜欢了谁
3楼-- · 2018-12-31 06:39

Simple and elegant:

history.replaceState({}, document.title, ".");  // replace / with . to keep url
查看更多
路过你的时光
4楼-- · 2018-12-31 06:40

Initial question:

window.location.href.substr(0, window.location.href.indexOf('#'))

or

window.location.href.split('#')[0]

both will return the URL without the hash or anything after it.

With regards to your edit:

Any change to window.location will trigger a page refresh. You can change window.location.hash without triggering the refresh (though the window will jump if your hash matches an id on the page), but you can't get rid of the hash sign. Take your pick for which is worse...

MOST UP-TO-DATE ANSWER

The right answer on how to do it without sacrificing (either full reload or leaving the hash sign there) is down here. Leaving this answer here though with respect to being the original one in 2009 whereas the correct one which leverages new browser APIs was given 1.5 years later.

查看更多
人间绝色
5楼-- · 2018-12-31 06:40
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
查看更多
人气声优
6楼-- · 2018-12-31 06:42
<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>

put this code on head section

查看更多
零度萤火
7楼-- · 2018-12-31 06:43

(Too many answers are redundant and outdated.) The best solution now is this:

history.replaceState(null, null, ' ');
查看更多
登录 后发表回答