javascript窗口位置href不带哈希?
我有: 提供javascript窗口位置href不带哈希?,javascript,location,substring,Javascript,Location,Substring,我有: 提供http://example.com/something#hash 没有#散列,获取整个路径的最佳和最简单的方法是什么 var uri = window.location.href; 我尝试使用location.origin+location.pathname,但这在每个浏览器中都不起作用。我尝试使用location.protocol+'/'+location.host+location.pathname,这对我来说似乎是一个糟糕的解决方案 最好和最简单的方法是什么?也许我查询lo
http://example.com/something#hash
没有#散列
,获取整个路径的最佳和最简单的方法是什么
var uri = window.location.href;
我尝试使用location.origin+location.pathname
,但这在每个浏览器中都不起作用。我尝试使用location.protocol+'/'+location.host+location.pathname
,这对我来说似乎是一个糟糕的解决方案
最好和最简单的方法是什么?也许我查询location.hash并尝试从uri中substr()这个?
location.protocol+'/'+location.host+location.pathname
是正确的语法,如果您不关心端口号或查询字符串
如果你真的在乎:
或
您也可以只执行一个location.href.replace(location.hash,“”)
或者创建一个:
constURL=新url(“https://www.somepage.com/page.hmtl#anchor”/(location.href);
console.log(url)
url.hash=“”;
console.log(url)
较短的解决方案:
- 没有查询字符串和散列
location.href.split(location.search | | | location.hash | |/[?#]/)[0]
- 仅不带hash
location.href.split(location.hash | | |“#”)[0]
(我通常使用第一个)通用方法也是较小的吗
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.hash;
// Returns #hash
location.href=window.location.href.split(“在此处写入要在URL中删除的代码”)[0]+“在此处写入最终目的地”;
您丢失了查询字符串(如果有查询字符串的话),似乎location.host包含了端口。关于.replace(location.hash,”)
的最后一点非常棒,这正是我想要的。@GrigoryKalabin-应该仍然有效:var url=”http://example.com#example"; var lnk=document.createElement(“a”);lnk.href=url;警报(lnk.hash)
location.href.replace(location.hash,“”)将无法正常工作,因为:将“”作为哈希;将“#a”作为散列;window.location.href.split(“#”)[0]是一个正确的解决方案。(location+”).href.replace(location.hash,”)
在firefox中工作(location不是一个常规字符串),但要注意当url是somehting.com/#时location.hash
是“”;令我惊讶的是,如果location.hash
包含在url的其他地方,这不会中断。例如,“”。因为location.hash
包含前导“#”。除此之外,当散列为空时,如上所述。顺便说一句,如果您这样做只是为了链接到同一页面上的#部分
,只需将链接href设置为#部分
。您不需要获取页面的基本url,然后在末尾连接散列。散列符号不包含在该数组的第二部分中,因为它确实包含一个修复程序!:-)这不管用<代码>“foo#bar#baz”。拆分(“#”)==“bar”对于散列,只需使用location.hash
。您好@Vittrix欢迎使用SO!请阅读,并尝试加入一些注释,说明与已接受的答案相比,您的答案有哪些不同之处或更好!
location.protocol+'//'+
location.host+
location.pathname+
(location.search?location.search:"")
location.protocol+'//'+
location.hostname+
(location.port?":"+location.port:"")+
location.pathname+
(location.search?location.search:"")
location.href.replace(location.hash,"")
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.hash;
// Returns #hash
location.href.split(/\?|#/)[0]