没有参数的当前URL,hash,http(s):// [英] Current URL without parameters, hash, http(s)://
问题描述
我正在寻找一种在Javascript中获取当前文档的URL的简洁方法。
I'm looking for a neat way of getting the URL of the current document in Javascript.
- 网址应该是干净的参数(?parameter1 = bla& parameter2 = bla)
- URL应该是干净的哈希标签(#jumppoint)
- http / https应该是删除/合并为http
我知道我可以使用location.href获取当前URL,然后使用一些正则表达式来清理它但也许有一个更好/更清洁的解决方案摆脱垃圾?
I know i can get the current URL with location.href and then use some regular expressions to clean it up but maybe there is a nicer/cleaner solution for getting rid of the junk?
推荐答案
还有许多其他参数而不是 href
在 window.location
中。请参阅此处的完整参考: https://developer.mozilla.org/en/DOM/window.location
There are many other parameters than the href
in window.location
. See full reference here: https://developer.mozilla.org/en/DOM/window.location
作为首发的人可能是 window.location.hostname
:
主机名(没有端口号或方括号
括号)。
"the host name (without the port number or square brackets)."
从示例网址 http:// [www.example.com]:80 / search?q = devmo #test
主机名将是 www.example.com
。
From the example URL http://[www.example.com]:80/search?q=devmo#test
the hostname will be www.example.com
.
如果您还想包含路径并强制使用http://协议,尝试:
If you also want to include the path and force a http:// protocol, try:
'http://' + window.location.hostname + window.location.pathname;
作为旁注,从window.location获取与其他URL相同的参数的巧妙技巧是创建一个空锚:
As a side note, a nifty trick to get the same parameters from another URL than the window.location is to create an empty anchor:
var a = document.createElement('a');
a.href = 'http://www.example.com:80/search?q=devmo#test';
console.log('http://' + a.hostname + a.pathname);
这篇关于没有参数的当前URL,hash,http(s)://的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!