mat*_*att 72 javascript location substring
我有:
var uri = window.location.href;
Run Code Online (Sandbox Code Playgroud)
这提供了 http://example.com/something#hash
什么是最好和最简单的方法来获得没有的整个路径#hash
?
uri = http://example.com/something#hash
nohash = http://example.com/something
Run Code Online (Sandbox Code Playgroud)
我尝试使用location.origin+location.pathname
哪个在每个浏览器中都不起作用.我尝试使用location.protocol+'//'+location.host+location.pathname
这对我来说看起来像一个糟糕的解决方案.
最好和最简单的方法是什么?也许我查询location.hash并尝试从uri中substr()这个?
mpl*_*jan 77
location.protocol+'//'+location.host+location.pathname
如果您不关心端口号或查询字符串,则是正确的语法
如果你照顾:
https://developer.mozilla.org/en/DOM/window.location
location.protocol+'//'+
location.host+
location.pathname+
(location.search?location.search:"")
Run Code Online (Sandbox Code Playgroud)
要么
location.protocol+'//'+
location.hostname+
(location.port?":"+location.port:"")+
location.pathname+
(location.search?location.search:"")
Run Code Online (Sandbox Code Playgroud)
你也可以做一个 location.href.replace(location.hash,"")
Nic*_*unt 75
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.href.split("#")[1];
// Returns #hash
Run Code Online (Sandbox Code Playgroud)
小智 6
更短的解决方案:
没有查询字符串和哈希 location.href.split(location.search||location.hash||/[?#]/)[0]
只有没有哈希 location.href.split(location.hash||"#")[0]
(我通常使用第一个)