在我的项目中,我有许多包含不同格式的域名和子域名的字符串。
我需要一个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
[...]在每一种情况下,是否都有实现这一目标的功能?
发布于 2013-12-02 12:46:05
创建锚元素并使href字符串。
var a = document.createElement('a');
a.href = data;从里面找出主机名。
a.hostname类似地,您也可以获取协议和其他属性。
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;
}发布于 2013-12-02 12:42:24
是的,你可以使用document.location.hostname或document.location.host。
编辑啊,我现在明白了。
检查此链接:http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
function parseURL(url) {
var a = document.createElement('a');
a.href = url;
return {
source: url,
protocol: a.protocol.replace(':',''),
host: a.hostname,
port: a.port,
query: a.search,
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
hash: a.hash.replace('#',''),
path: a.pathname.replace(/^([^\/])/,'/$1'),
relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
segments: a.pathname.replace(/^\//,'').split('/')
};
}那么你所做的就是:
var url = "http://domain.com/blah/";
var urlObj = parseUrl(url);
var host = urlObj.host;发布于 2013-12-02 12:42:25
没有内置的功能,但你可以自己做。
此regexp与您发布的所有案例相匹配:
/:\/\/(.*?)\//http://regex101.com/r/dS8uK8
用法:
var str = 'http://mysite.eu/portal/';
var domain = str.match(/:\/\/(.*?)\//)[1];
console.log(domain); //"mysite.eu"https://stackoverflow.com/questions/20328571
复制相似问题