我有:
var uri = window.location.href;
提供http://example.com/something#hash
在没有#hash
的情况下获得整个路径的最佳和最简单方法是什么?
uri = http://example.com/something#hash
nohash = http://example.com/something
我尝试使用location.origin+location.pathname
,这在每个浏览器中都不起作用。我尝试使用location.protocol+'//'+location.host+location.pathname
,这看起来像是一种糟糕的解决方案。
最好和最简单的方法是什么?也许我查询location.hash并尝试从uri中使用substr()这个?
答案 0 :(得分:68)
location.protocol+'//'+location.host+location.pathname
是正确的语法
如果你照顾:
https://developer.mozilla.org/en/DOM/window.location
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,"")
答案 1 :(得分:68)
var uri = window.location.href.split("#")[0];
// Returns http://example.com/something
var hash = window.location.href.split("#")[1];
// Returns #hash
答案 2 :(得分:13)
location.href.replace(location.hash,"")
答案 3 :(得分:6)
更短的解决方案:
没有查询字符串和哈希location.href.split(location.search||location.hash||/[?#]/)[0]
仅限哈希location.href.split(location.hash||"#")[0]
(我通常使用第一个)
答案 4 :(得分:5)
通用方式也更小吗?
location.href.split(/\?|#/)[0]
答案 5 :(得分:0)
ES2020:
let [uri, hash] = location.href.split("#");
console.log(uri, hash);
location.hash = "#myhash";
[uri, hash] = location.href.split("#");
console.log(uri, hash);
答案 6 :(得分:-3)
location.href = window.location.href.split("write here your code to delete in your URL")[0] + "write here your final destination";