Get domain name without subdomains using JavaScript?

后端 未结 8 1553
陌清茗
陌清茗 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:00

    What about...

        function getDomain(){
            if(document.domain.length){
                var parts = document.domain.replace(/^(www\.)/,"").split('.');
    
                //is there a subdomain? 
                while(parts.length > 2){
                    //removing it from our array 
                    var subdomain = parts.shift();
                }
    
                //getting the remaining 2 elements
                var domain = parts.join('.');
    
                return domain.replace(/(^\.*)|(\.*$)/g, "");
            }
            return '';
        }
    
    0 讨论(0)
  • 2020-11-29 07:02

    Here is a working JSFiddle

    My solution works with the assumption that the root hostname you are looking for is of the type "abc.xyz.pp".

    extractDomain() returns the hostname with all the subdomains. getRootHostName() splits the hostname by . and then based on the assumption mentioned above, it uses the shift() to remove each subdomain name. Finally, whatever remains in parts[], it joins them by . to form the root hostname.

    Javascript

    var urlInput = "http://one.two.roothost.co.uk/page.html";
    
    function extractDomain(url) {
        var domain;
        //find & remove protocol (http, ftp, etc.) and get domain
        if (url.indexOf("://") > -1) {
            domain = url.split('/')[2];
        } else {
            domain = url.split('/')[0];
        }
    
        //find & remove port number
        domain = domain.split(':')[0];
    
        return domain;
    }
    
    function getRootHostName(url) {
        var parts = extractDomain(url).split('.');
        var partsLength = parts.length - 3;
    
        //parts.length-3 assuming root hostname is of type abc.xyz.pp
        for (i = 0; i < partsLength; i++) {
            parts.shift(); //remove sub-domains one by one
        }
        var rootDomain = parts.join('.');
    
        return rootDomain;
    }
    
    document.getElementById("result").innerHTML = getRootHostName(urlInput);
    

    HTML

    <div id="result"></div>
    

    EDIT 1: Updated the JSFiddle link. It was reflecting the incorrect code.

    0 讨论(0)
  • 2020-11-29 07:07

    My solution worked for me: Get "gocustom.com" from "shop.gocustom.com"

    var site_domain_name = 'shop.gocustom.com';
    alert(site_domain_name);
    var strsArray = site_domain_name.split('.');
    var strsArrayLen = strsArray.length;
    alert(strsArray[eval(strsArrayLen - 2)]+'.'+strsArray[eval(strsArrayLen - 1)])
    
    0 讨论(0)
  • 2020-11-29 07:08

    Simplest solution:

    var domain='https://'+window.location.hostname.split('.')[window.location.hostname.split('.').length-2]+'.'+window.location.hostname.split('.')[window.location.hostname.split('.').length-1];
    alert(domain);

    0 讨论(0)
  • 2020-11-29 07:09

    Following is a solution to extract a domain name without any subdomains. This solution doesn't make any assumptions about the URL format, so it should work for any URL. Since some domain names have one suffix (.com), and some have two or more (.co.uk), to get an accurate result in all cases, we need to parse the hostname using the Public Suffix List, which contains a list of all public domain name suffixes.


    Solution

    First, include the public suffix list js api in a script tag in your HTML, then in JavaScript to get the hostname you can call:

    var parsed = psl.parse('one.two.roothost.co.uk');
    console.log(parsed.domain);
    

    ...which will return "roothost.co.uk". To get the name from the current page, you can use location.hostname instead of a static string:

    var parsed = psl.parse(location.hostname);
    console.log(parsed.domain);
    

    Finally, if you need to parse a domain name directly out of a full URL string, you can use the following:

    var url = "http://one.two.roothost.co.uk/page.html";
    url = url.split("/")[2]; // Get the hostname
    var parsed = psl.parse(url); // Parse the domain
    document.getElementById("output").textContent = parsed.domain;
    

    JSFiddle Example (it includes the entire minified library in the jsFiddle, so scroll down!): https://jsfiddle.net/6aqdbL71/2/

    0 讨论(0)
  • 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
      }
    
    0 讨论(0)
提交回复
热议问题