从URL获取二级域名 [英] Get second level domain name from URL

查看:300
本文介绍了从URL获取二级域名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法从网址

获取顶级域名,例如 https://images.google.com/blah =>google

for e.g., "https://images.google.com/blah" => "google"

我发现了这个:

var domain = new URL(pageUrl).hostname; 

但是它给了我images.google.com而不仅仅是google。

but it gives me "images.google.com" instead of just google.

我所拥有的单元测试是:

Unit tests I have are:

https://images.google.com   => google
https://www.google.com/blah => google
https://www.google.co.uk/blah => google
https://www.images.google.com/blah => google


推荐答案

你可以这样做:

location.hostname.split('.').pop()

编辑

看到您的问题的更改,您需要一份所有TLD列表要匹配和删除主机名,那么你可以使用 split('。')。pop()

Saw the change to your question, you would need a list of all TLDs to match against and remove from the hostname, then you could use split('.').pop()

// small example list
var re = new RegExp('\.+(co.uk|me|com|us)')
var secondLevelDomain = 'https://www.google.co.uk'.replace(re, '').split('.').pop()

这篇关于从URL获取二级域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆