Get The Current Domain Name With Javascript (Not the path, etc.)

前端 未结 17 2153
情歌与酒
情歌与酒 2020-12-04 05:43

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to de

相关标签:
17条回答
  • 2020-12-04 06:18

    If you want to get domain name in JavaScript, just use the following code:

    var domain_name = document.location.hostname;
    alert(domain_name);
    

    If you need to web page URL path so you can access web URL path use this example:

    var url = document.URL;
    alert(url);
    
    0 讨论(0)
  • 2020-12-04 06:19

    Use

    document.write(document.location.hostname)​
    

    window.location has a bunch of properties. See here for a list of them.

    0 讨论(0)
  • 2020-12-04 06:20

    for my case the best match is window.location.origin

    0 讨论(0)
  • 2020-12-04 06:22
    function getDomain(url, subdomain) {
        subdomain = subdomain || false;
    
        url = url.replace(/(https?:\/\/)?(www.)?/i, '');
    
        if (!subdomain) {
            url = url.split('.');
    
            url = url.slice(url.length - 2).join('.');
        }
    
        if (url.indexOf('/') !== -1) {
            return url.split('/')[0];
        }
    
        return url;
    }
    

    Examples

    • getDomain('http://www.example.com'); // example.com
    • getDomain('www.example.com'); // example.com
    • getDomain('http://blog.example.com', true); // blog.example.com
    • getDomain(location.href); // ..

    Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'

    0 讨论(0)
  • 2020-12-04 06:22

    If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.

    The following code does this:

    var firstDot = window.location.hostname.indexOf('.');
    var tld = ".net";
    var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
    var domain;
    
    if (isSubdomain) {
        domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
    }
    else {
      domain = window.location.hostname;
    }
    

    http://jsfiddle.net/5U366/4/

    0 讨论(0)
提交回复
热议问题