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

前端 未结 17 2233
情歌与酒
情歌与酒 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: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/

提交回复
热议问题