javascript窗口位置href没有哈希?

mat*_*att 72 javascript location substring

我有:

var uri = window.location.href;
Run Code Online (Sandbox Code Playgroud)

这提供了 http://example.com/something#hash

什么是最好和最简单的方法来获得没有的整个路径#hash

uri    = http://example.com/something#hash
nohash = http://example.com/something
Run Code Online (Sandbox Code Playgroud)

我尝试使用location.origin+location.pathname哪个在每个浏览器中都不起作用.我尝试使用location.protocol+'//'+location.host+location.pathname这对我来说看起来像一个糟糕的解决方案.

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

mpl*_*jan 77

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

如果你照顾:

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

location.protocol+'//'+
  location.host+
  location.pathname+
 (location.search?location.search:"")
Run Code Online (Sandbox Code Playgroud)

要么

location.protocol+'//'+
  location.hostname+
 (location.port?":"+location.port:"")+
  location.pathname+
 (location.search?location.search:"")
Run Code Online (Sandbox Code Playgroud)

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

  • 最后一点关于`.replace(location.hash,'')`非常精彩,正是我在追踪的东西. (14认同)
  • location.href.replace(location.hash,"")将无法正常工作,因为:http://example.com#example#将''作为哈希; http://example.com#example#a将'#a'作为哈希值; window.location.href.split('#')[0]是一个正确的解决方案. (6认同)

Nic*_*unt 75

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

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

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

// Returns #hash
Run Code Online (Sandbox Code Playgroud)

  • 对于哈希,只需使用“ location.hash”。 (3认同)
  • 哈希符号不包含在该数组的第二部分中 (2认同)
  • 这行不通。`“ foo#bar#baz” .split(“#”)==“ bar”` (2认同)

Que*_*tin 15

location.href.replace(location.hash,"")
Run Code Online (Sandbox Code Playgroud)


Ala*_*ois 7

通用的方式也越小吗?

location.href.split(/\?|#/)[0]
Run Code Online (Sandbox Code Playgroud)


小智 6

更短的解决方案:

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

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

(我通常使用第一个)