没有参数的当前URL,hash,http(s)://

bar*_*iir 34 javascript string url

我正在寻找一种在Javascript中获取当前文档的URL的简洁方法.

  • URL应该是干净的参数(?parameter1 = bla¶meter2 = bla)
  • URL应该是干净的哈希标签(#jumppoint)
  • 应将http/https删除/合并到http中

我知道我可以使用location.href获取当前的URL,然后使用一些正则表达式来清理它,但也许有一个更好/更清洁的解决方案来摆脱垃圾?

Dav*_*ing 57

除了hrefin 之外还有许多其他参数window.location.请参阅此处的完整参考:https://developer.mozilla.org/en/DOM/window.location

您正在寻找的首发可能是window.location.hostname:

"主机名(没有端口号或方括号)."

从示例URL中http://[www.example.com]:80/search?q=devmo#test,主机名将是www.example.com.

如果您还想包含路径并强制使用http://协议,请尝试:

'http://' + window.location.hostname + window.location.pathname;
Run Code Online (Sandbox Code Playgroud)

作为旁注,从window.location获取与另一个URL相同的参数的一个很好的技巧是创建一个空锚:

var a = document.createElement('a');
a.href = 'http://www.example.com:80/search?q=devmo#test';

console.log('http://' + a.hostname + a.pathname);
Run Code Online (Sandbox Code Playgroud)


Kev*_*haw 32

没有给出的答案解决了协议可以是http或https的事实,如OP标题中所述.为了适应这个,我建议:

document.location.protocol +"//"+ document.location.hostname + document.location.pathname
Run Code Online (Sandbox Code Playgroud)

  • 如果您的 URL 中有端口号,则此解决方案会导致端口号丢失,即 http://localhost:49346/ 变为 http://localhost。 (2认同)

use*_*621 5

位置的对象得到你所需要的

window.location.hostname + window.location.pathname
Run Code Online (Sandbox Code Playgroud)