题意:在JavaScript中,如果你想要获取window.location.href的值但不包括其哈希(hash)部分(即URL中#符号及其后面的内容)

问题背景:

I have:        

var uri = window.location.href;

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

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

要获取完整的URL路径(不包括#hash部分)

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

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

我尝试使用 location.origin + location.pathname,但这并不在所有浏览器中有效。你又尝试使用 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中截取它?

问题解决:

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

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

If you do care:        如果你确实关心

Window: location property - Web APIs | MDN

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

你也可以使用location.href.replace(location.hash,""),这会从第一个#开始,无论字符串中是否还有其他#字符,都会删除该符号及其之后的所有内容

Alternatively create a URL object:

另外,你也可以创建一个URL对象

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

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐