Get the domain name of the subdomain Javascript

后端 未结 5 778
再見小時候
再見小時候 2020-12-05 07:15

How i can get the domain name example.com from the set of possible subdomains sub1.example.com sub2.example.com sub3.example.com

5条回答
  •  旧巷少年郎
    2020-12-05 07:20

    The accepted answer will work to get the second level domain. However, there is something called "public suffixes" that you may want to take into account. Otherwise, you may get unexpected and erroneous results.

    For example, take the domain www.amazon.co.uk. If you just try getting the second level domain, you'll end up with co.uk, which is probably not what you want. That's because co.uk is a "public suffix", which means it's essentially a top level domain. Here's the definition of a public suffix, taken from https://publicsuffix.org:

    A "public suffix" is one under which Internet users can (or historically could) directly register names.

    If this is a crucial part of your application, I would look into something like psl (https://github.com/lupomontero/psl) for domain parsing. It works in nodejs and the browser, and it's tested on Mozilla's maintained public suffix list.

    Here's a quick example from their README:

    var psl = require('psl');
    
    // TLD with some 2-level rules.
    psl.get('uk.com'); // null);
    psl.get('example.uk.com'); // 'example.uk.com');
    psl.get('b.example.uk.com'); // 'example.uk.com');
    

提交回复
热议问题