没有散列的 javascript 窗口位置 href?

我有:

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 中调用 subr () this?

87897 次浏览

location.protocol+'//'+location.host+location.pathname is the correct syntax if you do not care about port number or querystring

If you do care:

https://developer.mozilla.org/en/DOM/window.location

location.protocol+'//'+
location.host+
location.pathname+
(location.search?location.search:"")

or

location.protocol+'//'+
location.hostname+
(location.port?":"+location.port:"")+
location.pathname+
(location.search?location.search:"")

You can also just do a location.href.replace(location.hash,"")
It will remove EVERYTHING from the FIRST # and on regardless of other hash characters in the string

Alternatively create a URL object:

const url = new URL("https://www.somepage.com/page.hmtl#anchor") //(location.href);
console.log(url)
url.hash="";
console.log(url)

location.href.replace(location.hash,"")
var uri = window.location.href.split("#")[0];


// Returns http://example.com/something


var hash = window.location.hash;


// Returns #hash

Shorter solutions:

  • without query string and hash location.href.split(location.search||location.hash||/[?#]/)[0]

  • only without hash location.href.split(location.hash||"#")[0]

(I usually use the first one)

Is the universal way also the smaller?

location.href.split(/\?|#/)[0]
location.href = window.location.href.split("write here your code to delete in your URL")[0] + "write here your final destination";

ES2020:

let [uri, hash] = location.href.split("#");
console.log(uri, hash);


location.hash = "#myhash";


[uri, hash] = location.href.split("#");
console.log(uri, hash);

I was looking for this answer:

`${window.location.origin}${window.location.pathname}${window.location.search}`