How to get domain name only using javascript?

后端 未结 11 687
长发绾君心
长发绾君心 2020-12-02 23:57

I want to get domain name only using javascript. Ex

vn.search.yahoo.com -> yahoo
vn.search.yahoo.com.vn -> yahoo
sub1.sub2.sub3.abcdef.co.uk -> abcd         


        
11条回答
  •  盖世英雄少女心
    2020-12-03 00:50

    I was looking for something that would work for the majority of cases, without having to maintain the TLD list (and skip it's size!). It seems to me that you can do this pretty accurately by looking instead at the Second-Level Domain for common ones:

    function getDomainName(domain) {
        var parts = domain.split('.').reverse();
        var cnt = parts.length;
        if (cnt >= 3) {
            // see if the second level domain is a common SLD.
            if (parts[1].match(/^(com|edu|gov|net|mil|org|nom|co|name|info|biz)$/i)) {
                return parts[2] + '.' + parts[1] + '.' + parts[0];
            }
        }
        return parts[1]+'.'+parts[0];
    }
    

    Fiddle & Tests @ http://jsfiddle.net/mZPaf/2/

    Critiques/thoughts welcome.

提交回复
热议问题