在我的项目中,我有很多包含各种格式的域名和子域名的字符串。
我需要一个 JavaScript 函数,它只返回字符串中的第一级域名,例如:
string: https://www.example.com/test/intro.php
return: www.example.com
string: http://www.test.fr/
return: www.test.fr
string: http://mysite.eu/portal/
return: mysite.eu
[...]
是否存在在每种情况下都能实现此目标的函数?
最佳答案
创建 anchor 元素并使 href 成为字符串。
var a = document.createElement('a');
a.href = data;
从中获取主机名。
a.hostname
同样,您也可以获取协议(protocol)和其他属性。
a.protocol; // => "http:"
a.host; // => "example.com:5000"
a.hostname; // => "example.com"
a.port; // => "5000"
a.pathname; // => "/pathname/"
a.hash; // => "#value"
a.search; // => "?q=test"
这是回答你问题的函数
function getDomainFromURL(data) {
var a = document.createElement('a');
a.href = data;
return a.hostname;
}
关于javascript只返回字符串的一级域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20328571/