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

问题描述 投票:0回答:10

我有:

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() ?

javascript location substring
10个回答
115
投票
如果您不关心端口号或查询字符串,

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

无论字符串中的其他哈希字符如何,它将删除从第一个 # 开始的所有内容

或者创建一个 URL 对象:

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


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

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

var hash = window.location.hash;

// Returns #hash

22
投票
location.href.replace(location.hash,"")

9
投票

万能路也是越小吗?

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

8
投票

更短的解决方案:

  • 没有查询字符串和哈希

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

  • 仅无哈希

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

(我一般用第一个)


1
投票

我一直在寻找这个答案:

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

1
投票

我喜欢让本机代码尽可能地完成繁重的工作。我开始认为浏览器可以比我们做出最佳猜测更好地识别 URL 的各个部分。因此,这是供您考虑的另一种变体:

new URL('#', location.href).slice(0, -1)

我想这需要一点解释:正在发生的事情是我们正在构建一个 URL 对象,其中当前 URL 上的空哈希作为基础,即如果存在哈希,它将被空哈希替换。然后,我们从隐式转换字符串(URL 对象的 href)中删除最后一个字符(“#”)。


0
投票

ES2020:

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

location.hash = "#myhash";

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


0
投票

我更喜欢这种简短的单行代码,它直接返回想要的结果,而不是创建一个数组。

仅删除哈希值 (#hash):

location.href.replace(/#.*$/, '')

要删除哈希 (#hash) 和查询参数 (?query=value&...):

location.href.replace(/(\?|#).*$/, '')

这是用于替换第一个 ? 的正则表达式 (

/.../
) (
\?
) 或 (
(...|...)
) # (
#
),所有字符 (
.*
) 直到字符串结尾 (
$
),由空字符串 (
''
) 组成。


-3
投票
location.href = window.location.href.split("write here your code to delete in your URL")[0] + "write here your final destination";
© www.soinside.com 2019 - 2024. All rights reserved.