gpt4 book ai didi

javascript - 从 URL 获取域名问题

转载 作者:行者123 更新时间:2023-11-30 12:38:11 28 4
gpt4 key购买 nike

我需要一些 JavaScript 帮助我有以下功能

domain: function(){
var a = document.createElement('a');
a.href = this.url;
return a.hostname;
}

这很好,但是当 this.url 类似于 google.com(没有 http 或 www)时,我返回的是 localhost有什么想法吗?

最佳答案

如果缺少协议(protocol),您可以添加协议(protocol),这样您的 URL 将始终有效

domain: function(d){
var a = document.createElement('a');
a.href = this.url.match(/^[a-zA-Z]+:\/\//) ? this.url : 'http://' + this.url;
return a.hostname;
}

FIDDLE

如果传递的 url 只是 google.com 而没有协议(protocol),则它被认为是相对 URL,因此 anchor 最终为

<a href="http://localhost/google.com"></a>

而如果 URL 是绝对的并且包含协议(protocol),则它最终为

<a href="http://google.com"></a>

这就是为什么您必须在缺少协议(protocol)的情况下添加协议(protocol)。

关于javascript - 从 URL 获取域名问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25399011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com