Determine domain name in JavaScript?

Readable Method:

You can use endsWith() to compare the end of the hostname string with the domain name:

location.hostname === 'stackexchange.com' || location.hostname.endsWith('.stackexchange.com')

Note: This requires ECMAScript 6 (ES6) support.

Short Method:

Or if you would prefer to use a regex with the test() method, you can use:

/(^|\.)stackexchange\.com$/.test(location.hostname)

Split/Join Array-to-String Method:

Additionally, you can also split() the hostname into an array based on the . character. Then you can take the last two elements (the domain name and extension) using slice(), and join() them back together with the . character as the separator, which will allow you to compare directly to the expected domain name:

location.hostname.split('.').slice(-2).join('.') === 'stackexchange.com'

This will return true for the following types of URLs:

  • https://stackexchange.com/
  • https://stackexchange.com/tour
  • https://dba.stackexchange.com/
  • https://dba.stackexchange.com/tour

The first and third should be simple and quick. Of the two, I don't think it really matters as long as you're just testing the domain.

If you're testing a sub-domain, then consider that document.domain be modified in javascript, while window.location.hostname can't.


All of ur solutions aren't efficient! they will basically match everything that contains the domain name.. e.g. lets say the domain is "domain.com"

  • `http://prefixdomain.com`
  • `http://domain.com.jo`
  • sub-domains `http://sub.domain.com`
  • paths: `http://whatever.com/domain.com`

so best solution would be

function isEquals(myhost){
              var hostName = window.location.hostname.split('.');
              myhost = myhost.split(".");
              //handle stuff like site:.com or ..com
              for (var x in myhost)
                if (myhost[x] == "") myhost.splice(x,1);

          //j is where to start comparing in the hostname of the url in question
          var j = hostName.length - myhost.length;
          for(var i in myhost)
          {
              //if j is undefined or doesn't equal the hostname to match return false 
              if (!hostName[j] || hostName[j].toLowerCase() != host[i].toLowerCase())
                  return false;
              j++;
          }
          return true;
      }

Best and most readable would be:

if(location.hostname == "mysite.com"){

}

Update:

Or as Patrick pointed out if you are only looking for part of the domain name I would use match.

if(location.hostname.match('mysite')){} // will return null if no match is found

Tags:

Javascript

Dns