Get domain name without subdomains using JavaScript?

后端 未结 8 1572
陌清茗
陌清茗 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 '';
        }
    

提交回复
热议问题