Javascript / Regex仅查找没有子域的根域名 [英] Javascript/Regex for finding just the root domain name without sub domains
问题描述
我有一个搜索,发现很多类似的正则表达式,但不完全是我需要的。
I had a search and found lot's of similar regex examples, but not quite what I need.
我想要能够传入以下urls并返回结果:
I want to be able to pass in the following urls and return the results:
-
www.google.com 返回 google.com
sub.domains.are.cool.google.com 返回 google.com
doesntmatterhowlongasubdomainis.idont.wantit.google.com
返回 google.com
sub.domain.google.com/no/thanks 返回 google.com
希望有意义:)
提前感谢-James
Hope that makes sense :) Thanks in advance!-James
推荐答案
您不能用正则表达式执行此操作,因为您不知道后缀中有多少个块。
You can't do this with a regular expression because you don't know how many blocks are in the suffix.
例如 google.com 的后缀为 com 。要从 subdomain.google.com 访问 google.com ,您必须使用最后两个块 - 一个用于后缀,一个用于 google 。
For example google.com has a suffix of com. To get from subdomain.google.com to google.com you'd have to take the last two blocks - one for the suffix and one for google.
如果您将此逻辑应用于 subdomain.google.co.uk ,尽管最终会出现 co.uk
If you apply this logic to subdomain.google.co.uk though you would end up with co.uk.
您实际上需要从列表中查找后缀,如 http://publicsuffix.org/
You will actually need to look up the suffix from a list like http://publicsuffix.org/
这篇关于Javascript / Regex仅查找没有子域的根域名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!