jquery, domain, get URL

前端 未结 11 2079
滥情空心
滥情空心 2020-12-12 10:04

How can I get the domain name with jquery ??

相关标签:
11条回答
  • 2020-12-12 10:55

    If you need from string, like me, use this function - it really works.

    function getHost(url)
    {
        var a = document.createElement('a');
        a.href = url;
        return a.hostname;
    }
    

    But note, if there is a subdomain (e.g. www.) in the URL it will get returned with the hostname. Conversely, if there is no subdomain the hostname will not have one either.

    0 讨论(0)
  • 2020-12-12 10:56
    var part = location.hostname.split('.');
    var subdomains = part.shift();
    var upperleveldomains = part.join('.');
    

    second-level-domain, you might use

    var sleveldomain = parts.slice(-2).join('.');
    
    0 讨论(0)
  • 2020-12-12 10:58

    check this

    alert(window.location.hostname);

    this will return host name as www.domain.com

    0 讨论(0)
  • 2020-12-12 11:00

    jQuery is not needed, use simple javascript:

    document.domain
    
    0 讨论(0)
  • 2020-12-12 11:02

    EDIT:

    If you don't need to support IE10, you can simply use: document.location.origin

    Original answer, if you need legacy support

    You can get all this and more by inspecting the location object:

    location = {
      host: "stackoverflow.com",
      hostname: "stackoverflow.com",
      href: "http://stackoverflow.com/questions/2300771/jquery-domain-get-url",
      pathname: "/questions/2300771/jquery-domain-get-url",
      port: "",
      protocol: "http:"
    }
    

    so:

    location.host 
    

    would be the domain, in this case stackoverflow.com. For the complete first part of the url, you can use:

    location.protocol + "//" + location.host
    

    which in this case would be http://stackoverflow.com

    No jQuery required.

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