我有网址http://somesubdomain.domain.com (子域可能会有所不同,域总是相同的)。需要获取子域并使用greasemonkey重新加载页面,比如domain.com/some/path/here/somesubdomain (或者打开一个新窗口,URL是domain.com/some/path/here/somesubdomain,随便什么)。
发布于 2009-08-15 20:25:24
var full = window.location.host
//window.location.host is subdomain.domain.com
var parts = full.split('.')
var sub = parts[0]
var domain = parts[1]
var type = parts[2]
//sub is 'subdomain', 'domain', type is 'com'
var newUrl = 'http://' + domain + '.' + type + '/your/other/path/' + subDomain
window.open(newUrl);
发布于 2019-06-23 09:07:57
除了@jlbang提到的情况之外,这在大多数情况下都可以工作
const split=location.host.split(".");
let subdomain="";
let domain="";
if(split.length==1){//localHost
domain=split[0];
}else if(split.length==2){//sub.localHost or example.com
if(split[1].includes("localhost")){//sub.localHost
domain=split[1];
subdomain=split[0];
}else{//example.com
domain=split.join(".");
}
}else{//sub2.sub.localHost or sub2.sub.example.com or sub.example.com or example.com.ec sub.example.com.ec or ... etc
const last=split[split.length-1];
const lastLast=split[split.length-2];
if(last.includes("localhost")){//sub2.sub.localHost
domain=last;
subdomain=split.slice(0,split.length-1).join(".");
}else if(last.length==2 && lastLast.length<=3){//example.com.ec or sub.example.com.ec
domain=split.slice(split.length-3,split.length).join(".");
if(split.length>3){//sub.example.com.ec
subdomain=split.slice(0,split.length-3).join(".");
}
}else{//sub2.sub.example.com
domain=split.slice(split.length-2,split.length).join(".");
subdomain=split.slice(0,split.length-2).join(".");
}
}
const newUrl = 'http://example.com/some/path/here/' + subdomain
发布于 2021-05-10 22:12:09
我将Vlad的解决方案改编为现代打字版本:
const splitHostname = (
hostname: string
): { domain: string; type: string; subdomain: string } | undefined => {
var urlParts = /([a-z-0-9]{2,63}).([a-z.]{2,5})$/.exec(hostname);
if (!urlParts) return;
const [, domain, type] = urlParts;
const subdomain = hostname.replace(`${domain}.${type}`, "").slice(0, -1);
return {
domain,
type,
subdomain,
};
};
https://stackoverflow.com/questions/1282726
复制相似问题