Get domain name without subdomains using JavaScript?

后端 未结 8 1552
陌清茗
陌清茗 2020-11-29 06:48

How to get the domain name without subdomains?

e.g. if the url is \"http://one.two.roothost.co.uk/page.html\" how to get \"roothost.co.uk\"?

8条回答
  •  离开以前
    2020-11-29 07:10

    You can use parse-domain to do the heavy lifting for you. This package considers the public suffix list and returns an easy to work with object breaking up the domain.

    Here is an example from their readme:

      npm install parse-domain
    
      import { parseDomain, ParseResultType } from 'parse-domain';
    
      const parseResult = parseDomain(
        // should be a string with basic latin characters only. more details in the readme
        'www.some.example.co.uk',
      );
    
      // check if the domain is listed in the public suffix list
      if (parseResult.type === ParseResultType.Listed) {
        const { subDomains, domain, topLevelDomains } = parseResult;
    
        console.log(subDomains); // ["www", "some"]
        console.log(domain); // "example"
        console.log(topLevelDomains); // ["co", "uk"]
      } else {
        // more about other parseResult types in the readme
      }
    

提交回复
热议问题