How do I get the "meaningful" node of the domain name in JavaScript?

javascript, url

Solution

This is actually a trickier problem than it appears at first glance, because the number of domain components (technically "labels") you want depends on the domain name. See this:

http://www.onlineaspect.com/2011/03/17/detect-subdomains-using-effective-tlds/

The Mozilla project started a sister project to maintain a list of the effective TLD's; once you've identified the TLD, then what you are looking for is just one more label before that. The list is available here:

http://publicsuffix.org/

Problem

By "meaningful", I mean the part of the url by which most people identify the websites (is there a technical term for this?). For example, I'd like the code to return "gm" in all of the following cases: `gm.com`, `gm.net`, `gm.info`, `gm.com.uk`, `gm.co.jp`, `gm.jp` (these might not be real sites) Plus cases when any of the above has additional subdomains, e.g. `www.gm.com`, `www.cars.gm.com`, etc. It doesn't have to work with internationalized country code top-level domains (the ones with non-ASCII characters). The only way I can think of is to compare the highest-level label (e.g. `.com`) with the generic top-level domains, US top-level domains, and country code top-level domains, and then try to go left one label at a time. Still this requires me to know all the secondary level domain names under `.jp` (and all other countries), because otherwise I wouldn't be able to return the right value for both `www.yahoo.jp` and `yahoo.co.jp`. Is there a better way to do this?

Original source

Related problems