Javascript 没有哈希的javascript窗口位置href?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5818269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:02:40  来源:igfitidea点击:

javascript window location href without hash?

javascriptlocationsubstring

提问by matt

I have:

我有:

var uri = window.location.href;

That provides http://example.com/something#hash

那提供 http://example.com/something#hash

What's the best and easiest way to get the entire path without the #hash?

在没有#hash? 的情况下获得整个路径的最佳和最简单的方法是什么?

uri    = http://example.com/something#hash
nohash = http://example.com/something

I tried using location.origin+location.pathnamewhich doesn't work in every browser. I tried using location.protocol+'//'+location.host+location.pathnamewhich looks like kind of a crappy solution to me.

我尝试使用location.origin+location.pathnamewhich 不适用于每个浏览器。我尝试使用location.protocol+'//'+location.host+location.pathname这对我来说看起来像是一种蹩脚的解决方案。

What is the best and easiest way to do so? maybe I query for location.hash and try to substr() this from the uri?

最好和最简单的方法是什么?也许我查询 location.hash 并尝试从 uri 中 substr() 这个?

回答by mplungjan

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

location.protocol+'//'+location.host+location.pathname如果您不关心端口号或查询字符串,则是正确的语法

If you do care:

如果你真的关心:

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

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,"")

你也可以做一个 location.href.replace(location.hash,"")

Alternatively create a URL object:

或者创建一个URL 对象

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

回答by Nick Brunt

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

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

var hash = window.location.href.split("#")[1];

// Returns #hash

回答by Quentin

location.href.replace(location.hash,"")

回答by Alain Beauvois

Is the universal way also the smaller?

通用方式也越小?

location.href.split(/\?|#/)[0]

回答by Sebastien P.

Shorter solutions:

更短的解决方案:

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

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

  • 没有查询字符串和哈希 location.href.split(location.search||location.hash||/[?#]/)[0]

  • 只有没有哈希 location.href.split(location.hash||"#")[0]

(I usually use the first one)

(我一般用第一个)