从主机名中提取子域

Extract sub domain from hostname

本文关键字:提取 主机      更新时间:2023-09-26

我想要一种机制来从location.hostname中提取子域,这应该足以满足以下所有情况。

 1. example.com => return value is blank since no sub domain
 2. www.example.com => return value is blank since no sub domain
 3. test.example.com => return value should be test since this is the sub domain
 4. example.co.in => return value is blank since no sub domain
 5. www.example.co.in => return value is blank since no sub domain
 6. test.example.co.in => return value should be test since this is the sub domain
 7. 183.87.46.82 => return value is blank since IP passed

仅对于上述给定的情况,我需要处理。我不期望比这更多。最重要的是,我不需要提取任何嵌套的子域名,只有一级子域名就足够了。

这方面的任何想法都会有所帮助。

请考虑以下文章来定义有效的主机名:

https://www.rfc-editor.org/rfc/rfc952
https://www.rfc-editor.org/rfc/rfc1123此正则表达式应该对您有所帮助:

var regex = /^(?!www'.|'d{1,3}'.)[a-z0-9-]+?'.[a-z0-9-]{3,}'.[a-z0-9-]+?('.[a-z0-9-]+?)*?$/gi;
var hostname = "example.com";
console.log(hostname.match(regex));   // null
hostname = "www.example.com";
console.log(hostname.match(regex));   // null
hostname = "test.example.com";
console.log(hostname.match(regex));   // [ "test.example.com" ]
hostname = "www.example.com";
console.log(hostname.match(regex));   // null
hostname = "example.co.in";
console.log(hostname.match(regex));   // null
hostname = "www.example.co.in";
console.log(hostname.match(regex));   // null
hostname = "1test.example.co.in";
console.log(hostname.match(regex));   // [ "1test.example.co.in" ]
hostname = "187.162.10.12";
console.log(hostname.match(regex));   // null

https://jsfiddle.net/fknhumw3/

我个人确实认为www是一个子域,如果是"二级"域(.co.uk),我实际上会考虑co域名,以及它之前的任何内容都将是一个子域。

由于这并不能真正回答您的问题,因此这里有一种仅基于您的输入的方法(一旦您发现"二级"域(该列表未涵盖所有内容)比您想象的更难检测,您将对其进行修改)。

function subdomain(host) {
    var part = host.split('.').reverse(),
        index = 0;
    while (part[index].length === 2 || !index) {
        ++index;
    }
    ++index;
    return part.length > index && part[index] !== 'www' ? part[index] : '';
}

工作示例

这样做是应用一个非常生硬的规则,即"二级"域始终由 2x2 个字符(co.ukco.in 等)组成并过滤它们,然后跳到现在被认为是主域名并跳过它。如果最终我们确定的索引上有某些内容,并且它与"www"不匹配,则可以将其取回。

这只是一个例子,向您展示您的问题有多难,因为它需要一个最新的(如积极维护,策划的)"二级"域列表,否则您可能会失败。

我实际上唯一考虑的是some.deep.nested.sub.domain.com会给你sub而不是some

(另请注意,我根本没有主动阻止 ip 匹配,它恰好匹配 2x2 规则)。


我对你试图通过尝试隔离子域来解决的问题感到非常好奇,因为它本身没有任何意义。我可以想到您希望根据子域显示各种"昵称"的情况,但随后我发现您会知道预期的模式。从技术角度来看,只有子域是没有用的。

试试这个:

  ["example.com",
   "www.example.com",
   "test.example.com",
   "http://example.co.in",
   "http://www.example.co.in",
   "test.example.co.in",
   "http://183.87.46.82"]
        .filter(function(url){
            return url.match(/^(?!www).*'.(.*)'.co.*$/g)
        })

更新正则表达式

^(?!www).*'.(.*)'.co.*$