不带参数的当前URL,哈希,http://

Current URL without parameters, hash, http(s)://

本文关键字:哈希 URL http 参数      更新时间:2023-09-26

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

  • URL应该没有参数(?parameter1=bla&parameter2=bla)
  • URL应该没有散列标记(#jumppoint)
  • 应删除http/https/将其合并为http

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

除了window.location中的href,还有许多其他参数。请参阅此处的完整参考资料: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;

顺便说一句,从另一个URL而不是窗口获取相同参数的一个妙招是创建一个空锚:

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

所有给出的答案都没有说明协议可以是OP标题中的http或https。为了适应这一点,我建议:

document.location.protocol +"//"+ document.location.hostname + document.location.pathname

Location对象得到了您需要的

window.location.hostname + window.location.pathname

您有document.location对象,所以:

var oLoc = document.location,
    sUrl = oLoc.protocol + oLoc.hostname;
    // or "http://" + oLoc.hostname

您可以使用这些替换函数来删除哈希和搜索参数,并将https规范化为http:

url = url.replace(/#[^#]*$/, "").replace(/'?[^'?]*$/, "").replace(/^https:/, "http:");

或者,如果你真正想要的只是域和路径,你可以使用这个:

window.location.hostname + window.location.pathname

请尝试这个片段:

if (!window.location.origin){
  // For IE
  window.location.origin = window.location.protocol + "//" + (window.location.port ? ':' + window.location.port : '');      
}
url = window.location.origin + window.location.pathname;
document.write('Origin url: ' + url);

这个页面表明你可能可以使用window.location.host来获得你真正感兴趣的零件。不过我还没有测试过。

尝试:


window.location.hostname;