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

前端 未结 17 2152
情歌与酒
情歌与酒 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 05:56

    I figure it ought to be as simple as this:

    url.split("/")[2]

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

    Combining a few answers from the above, the following works really well for me for destroying Cookies:

      /**
       * Utility method to obtain the domain URI:
       */
      fetchDomainURI() {
        if (window.location.port.length > 0) {
          return window.location.hostname;
        }
        return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
      }
    

    Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.

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

    If you wish a full domain origin, you can use this:

    document.location.origin
    

    And if you wish to get only the domain, use can you just this:

    document.location.hostname
    

    But you have other options, take a look at the properties in:

    document.location
    
    0 讨论(0)
  • 2020-12-04 06:05

    What about this function?

    window.location.hostname.match(/\w*\.\w*$/gi)[0]
    

    This will match only the domain name regardless if its a subdomain or a main domain

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

    Since this question asks for domain name, not host name, a correct answer should be

    window.location.hostname.split('.').slice(-2).join('.')
    

    This works for host names like www.example.com too.

    0 讨论(0)
  • 2020-12-04 06:07
           Feel free to visit our “<a href="javascript:document.location.href=document.location.origin+'/contact-us'" title="Click to Contact Us" class="coded_link" ><span class="ui-icon ui-icon-newwin"></span>Contact</a>” link
    

    Indeed worked for me whereas I couldn't use PHP

    Just tested that it worked thanks to the approach mentioned above in some of the answers, so quick and verified that worked

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