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

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

    If you want the country domain name - for example to extract  .com  from  stackoverflow.com :

    (ES6):

    const getCountryDomainName = () => {
      let hostName = window.location.hostname;
      let lastDotIndex = hostName.lastIndexOf('.');
      let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
      return countryDomainName;
    }
    

    (ES5):

    function getCountryDomainName() {
      let hostName = window.location.hostname;
      let lastDotIndex = hostName.lastIndexOf('.');
      let countryDomainName = hostName.substr(lastDotIndex+1, hostName.length);
      return countryDomainName;
    }
    

    Then, just use the function to assign the value to a var:

    const countryDomainName = getCountryDomainName();
    

提交回复
热议问题