从主机名中提取子域
Extract sub domain from hostname
我想要一种机制来从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.uk
、co.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.*$
- chrome扩展更改主机/域警告
- 在数据提取完成之前进行页面渲染
- 如何在Javascript中从字符串中提取某些单词
- RegEx JavaScript:数字后的符号提取
- 如何在内联依赖项并将图像转换为dataURI的情况下完全提取网页
- Regex提取URL返回数组的一部分;未定义”;
- 如何提取“;href"最近列表项中的属性值
- 使用时刻.js从日期时间中提取时间
- 本地主机Typekit JS
- 通过javascript从会话中提取用户名
- HTML页面如何提取通过表单传递的参数
- 是否可以自动拉取“随机”;标签“;从一长串文本中提取
- Meteor应用程序无法运行-对象#<编译器>没有方法'主机'
- innerHTML的子字符串可以在初始调用时提取吗
- 如何使用phonegap从安卓设备中提取联系人的字母顺序
- 如何从特定页面中提取php变量值
- 如何使用jquery从url中提取主机名
- 从主机名中提取子域
- 从字符串中提取主机名名称
- 如何在onbeforeunload事件期间提取目标主机名