Javascript 如何替换url中的哈希

Javascript 如何替换url中的哈希,javascript,Javascript,如何替换这样的url http://test.com/#part1 致: 我知道location.hash,但它会检测url中是否有哈希。您可以使用replace() location.href = location.href.replace(location.hash,location.hash.substr(1)) 这是一个使用windows的分解版本。位置: var new_url = window.location.protocol + '//' + wind

如何替换这样的url

http://test.com/#part1
致:

我知道location.hash,但它会检测url中是否有哈希。

您可以使用replace()

location.href = location.href.replace(location.hash,location.hash.substr(1))
这是一个使用windows的分解版本。位置:

var new_url = window.location.protocol + '//'
            + window.location.hostname + '/'
            + window.location.pathname + '/'
            + window.location.hash.replace('#','','g') ;
或删除所有哈希:

var new_url = (window.location + '').replace('#','','g');

在我看来,使用正则表达式替换字符串是最好和最干净的解决方案

.replace( /#.*/, "");
范例

location.href = location.href.replace( /#.*/, "");

可能的副本是7年前公布的原始答案的副本。你应该改进或删除它,因为它没有增加任何价值。非常有用-我有一个不同于OP的问题-这个答案有帮助
.replace( /#.*/, "");
location.href = location.href.replace( /#.*/, "");