Get domain name without subdomains using JavaScript?

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

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

提交回复
热议问题