在我的项目中,我有许多字符串,包含各种格式的域名和子域名。
我需要一个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
[...]
是否存在能够在每种情况下实现此目标的功能?
答案 0 :(得分:3)
创建锚元素并使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;
}
答案 1 :(得分:0)
是的,您可以使用document.location.hostname
或document.location.host
。
编辑 Aaah,我现在明白了。
点击此链接: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;
答案 2 :(得分:0)
没有内置功能,但您可以创建自己的功能。
此正则表达式匹配您发布的所有案例:
/:\/\/(.*?)\//
用法:
var str = 'http://mysite.eu/portal/';
var domain = str.match(/:\/\/(.*?)\//)[1];
console.log(domain); //"mysite.eu"
答案 3 :(得分:0)
如果你不喜欢regexp(像我:),你可以试试这个:
function getDomain (inputString) {
var res = inputString.split("/");
return res[2];
}