在location.pathname前添加哈希值

Add hash before location.pathname

本文关键字:添加 哈希值 pathname location      更新时间:2023-09-26

我想在主域和/the/rest/of/url之间的URL中粘贴一个哈希值。

显然,我做得不对。

我使用

:

 window.location.hash = location.pathname;

希望用http://www.mybusinesssite.com/#/path/to/mypage代替http://www.mybusinesssite.com/path/to/mypage

我得到http://www.mybusinessite.com/path/to/mypage/#/path/to/my/page

http://www.mybusinesssite.com/#/path/to/mypage ?

Try

window.location = location.protocol + '//' + location.host + '/#' + location.pathname

如果你想改变显示的url,你可以使用推送状态,例如

history.pushState({}, "page x",  location.protocol + '//' + location.host + '/#' + location.pathname);

见https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Manipulating_the_browser_history

看这个

代码如下:

var a = document.createElement('a');
a.href = location.href;
var path = a.pathname;
a.pathname = "";
a.hash = path;
var resultUrl = a.href;

适用于我当前版本的IE, FireFox和Chrome。(IE是ie10兼容模式,所以它认为它是8)

这个适合我:

URL = window.location.protocol + '//' + window.location.host + '/#' + window.location.pathname;