Javascript 不带参数、哈希、http的当前URL://
我正在寻找一种用Javascript获取当前文档URL的简洁方法Javascript 不带参数、哈希、http的当前URL://,javascript,string,url,Javascript,String,Url,我正在寻找一种用Javascript获取当前文档URL的简洁方法 URL应该没有参数(?parameter1=bla¶meter2=bla) URL应该没有散列标签(#跳转点) http/https应被删除/合并为http 我知道我可以使用location.href获取当前URL,然后使用一些正则表达式来清理它,但也许有更好/更干净的解决方案来清除垃圾?除了窗口中的href之外,还有许多其他参数。location。请参阅此处的完整参考资料: 作为初学者,您需要的可能是窗口.locat
- URL应该没有参数(?parameter1=bla¶meter2=bla)
- URL应该没有散列标签(#跳转点)
- http/https应被删除/合并为http
我知道我可以使用location.href获取当前URL,然后使用一些正则表达式来清理它,但也许有更好/更干净的解决方案来清除垃圾?除了
窗口中的href
之外,还有许多其他参数。location
。请参阅此处的完整参考资料:
作为初学者,您需要的可能是窗口.location.hostname
:
“主机名(不带端口号或方框
括号)。”
从示例URLhttp://[www.example.com]:80/search?q=devmo#test
主机名将是www.example.com
如果还希望包含路径并强制使用http://协议,请尝试:
'http://' + window.location.hostname + window.location.pathname;
作为补充说明,从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);
页面表明您可能可以使用
window.location.host
获取您真正感兴趣的部件。不过,我还没有测试过它。您有文档。位置
对象,所以:
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
他们得到了你需要的东西
window.location.hostname + window.location.pathname
没有一个给出的答案解决了协议可以是http或https(如OPs标题中所示)这一事实。为此,我建议:
document.location.protocol +"//"+ document.location.hostname + document.location.pathname
请尝试以下代码段:
if(!window.location.origin){
//对于IE
window.location.origin=window.location.protocol+“/”+(window.location.port?:“+window.location.port:”);
}
url=window.location.origin+window.location.pathname;
document.write('originurl:'+url)代码>我很想投反对票,因为我把url的重要部分称为“垃圾”@道格拉斯的重要性是主观的。这是完全合理的,在这个函数的上下文中只有主机是相关的部分。pTROOCOL可以是FTP:同样,你需要考虑它吗?我想他们也想要路径名。@ JoFruty00 YEA,文档应该足以解决问题。但为了清楚起见,我也添加了这个选项。'http://'+window.location.hostname+window.location.pathname
您忘记了端口。很久以前就已经回答了。对于这个问题,这个答案是错误的,因为如果页面是https,它仍然会提供https://作为源协议-但是它应该将协议剥离/readd作为http。for IE代码中没有主机名吗?类似于window.location.origin=window.location.protocol+“/”+(window.location.port?:“+window.location.port:”)+“/”+window.location.hostname代码>是,但顺序不同:window.location.origin=window.location.protocol+“/”+window.location.hostname+(window.location.port?):“+window.location.port:”;如果URL中有端口号,此解决方案会导致端口号丢失,即变为。
document.location.protocol +"//"+ document.location.hostname + document.location.pathname