如何使用JavaScript从window.location(URL)中删除哈希而不刷新页面?

我有这样的URL: http://example.com#something ,我怎么删除#something ,而不会导致页面刷新?

我尝试了以下解决scheme:

 window.location.hash = ''; 

但是,这不会从URL中删除哈希符号#

最初的问题:

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

要么

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

两者都会返回没有散列的URL或任何后面的内容。

关于你的编辑:

window.location任何改变都会触发页面刷新。 您可以更改window.location.hash而不触发刷新(尽pipe如果您的哈希匹配页面上的ID,窗口将跳转),但是您不能摆脱散列符号。 把你的select,更糟的是…

最新的答案

如何做到这一点,而不牺牲(或者完全重载或者在那里留下散列符号)的正确答案在这里 。 尽pipe在这里留下了这个答案,但在2009年是原来的一个,而使用新的浏览器API的正确答案是在1.5年后给出的。

现在解决这个问题的可能性更大。 HTML5 History API允许我们操作地址栏来显示当前域中的任何URL。

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

工作演示: http : //jsfiddle.net/AndyE/ycmPt/show/

这适用于Chrome 9,Firefox 4,Safari 5,Opera 11.50 IE 10.对于不受支持的浏览器,您可以随时编写一个优雅的降级脚本,以便在可用的情况下使用它:

 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; } } 

所以你可以摆脱散列符号,但不是在所有的浏览器中。

注意:如果要replace浏览器历史logging中的当前页面,请使用replaceState()而不是pushState()

简单而优雅:

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

要删除散列,你可以尝试使用这个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); } } 

尝试以下操作:

 window.history.back(1); 

这也将删除结尾的散列。 例如: http : //test.com/123#abc – > http://test.com/123

 if(window.history.pushState) { window.history.pushState('', '/', window.location.pathname) } else { window.location.hash = ''; } 

以下情况如何?

window.location.hash=' '

请注意,我将散列设置为一个空格而不是空string。


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

window.location.hash='invalidtag'

但是,我发现上面的解决scheme是误导。 这似乎表明,在给定的名字上有一个锚点,虽然没有一个。 同时,使用空string会导致页面移动到顶部,这有时是不可接受的。 使用空格也可以确保每当URL被复制并加书签和再次访问时,页面通常在顶部,空间将被忽略。

而且,嘿,这是我在StackOverflow上的第一个答案。 希望有人发现它有用,它符合社区标准。

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

把这段代码放在头部

你可以用nullreplacehash

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