Derek 提供的答案适用于最常见的情况,但不适用于“xxx.xxx”子域或“host.co.uk”。 (同样,使用 window.location.host,也将检索未处理的端口号:http://www.w3schools.com/jsref/prop_loc_host.asp)
说实话,我看不到这个问题的完美解决方案。
就个人而言,我创建了一种我经常使用的主机名拆分方法,因为它涵盖了更多的主机名。
此方法将主机名拆分为{domain: "", type: "", subdomain: ""}
function splitHostname() {
var result = {};
var regexParse = new RegExp('([a-z\-0-9]{2,63})\.([a-z\.]{2,5})$');
var urlParts = regexParse.exec(window.location.hostname);
result.domain = urlParts[1];
result.type = urlParts[2];
result.subdomain = window.location.hostname.replace(result.domain + '.' + result.type, '').slice(0, -1);;
return result;
}
console.log(splitHostname());
此方法仅将子域作为字符串返回:
function getSubdomain(hostname) {
var regexParse = new RegExp('[a-z\-0-9]{2,63}\.[a-z\.]{2,5}$');
var urlParts = regexParse.exec(hostname);
return hostname.replace(urlParts[0],'').slice(0, -1);
}
console.log(getSubdomain(window.location.hostname));
// for use in node with express: getSubdomain(req.hostname)
这两种方法适用于最常见的域(包括 co.uk)
注意:子域末尾的slice 是为了去掉多余的点。
我希望这能解决你的问题。