首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取子域并使用greasemonkey将其加载到url

获取子域并使用greasemonkey将其加载到url
EN

Stack Overflow用户
提问于 2009-08-15 20:07:49
回答 4查看 47K关注 0票数 36

我有网址http://somesubdomain.domain.com (子域可能会有所不同,域总是相同的)。需要获取子域并使用greasemonkey重新加载页面,比如domain.com/some/path/here/somesubdomain (或者打开一个新窗口,URL是domain.com/some/path/here/somesubdomain,随便什么)。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 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);
票数 58
EN

Stack Overflow用户

发布于 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
票数 0
EN

Stack Overflow用户

发布于 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,
    };
  };
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1282726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档