22

What's the difference between using

if (document.domain.toLowerCase().indexOf("domainName") != -1)

and

if(window.location.href.match(/:\/\/(.[^/]+)/)[1].toLowerCase().indexOf("domainName") != -1)

and

if(window.location.hostname.toLowerCase().indexOf("domainName") != -1)

I'm just trying to match on a certain domainName and want to use the best approach.

Shafique
  • 1,828
  • 6
  • 26
  • 36
  • 1
    I would say the one that takes less amount of code (1st) is the best, but I don't have any experience with any of the three so...anyways don't rely too much on this, specially if you are checking for something related to security because an attacker could bypass it pretty easy – JCOC611 Jan 05 '11 at 23:47
  • 1
    By the way, your example will never work. You're calling toLowerCase() and then you're comparing to something that contains an upper case 'N'. :) – Ruan Mendes Jan 05 '11 at 23:56
  • ahhh yes good call, i was substituting the actual domain name with "domainName". but yes i've used all lowercase in that string that i'm matching on. – Shafique Jan 06 '11 at 15:40

5 Answers5

50

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
Josiah Ruddell
  • 29,697
  • 8
  • 65
  • 67
6

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:

Grant Miller
  • 27,532
  • 16
  • 147
  • 165
3

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;
      }
Amjad Masad
  • 4,035
  • 1
  • 21
  • 20
  • While this answer doesn't answer the question that was asked. The idea of breaking up the domain and comparing each individual parts is commendable. Although I am having trouble understanding second for loop. Partly because there is a typo ``host[i]`` probably should be ``myhost[i]``. Partly because ``var j`` is fixed and ``hostName[j]`` is being compared to every element of ``myhost[]``. I fail to see how this function would return ``true``. – iiminov Mar 23 '16 at 09:00
  • Say we're comparing ``http://sub.domain.com`` to ``http://sub.domain.com``. In this case ``j`` is ``0``. Therefore ``hostName[0]`` is ``'http://sub'`` which would get compared to ``myhost['http://sub', 'domain', 'com']``. The second condition of your ``if()`` statement in this case will be ``true`` on second and third iteration. ``!hostName[j]`` should alway return ``false`` unless ``hostName`` was ``undefined``. So even if you get through first iteration you will ``return false`` on subsequent iterations. – iiminov Mar 23 '16 at 09:02
  • I hope I am actually misunderstanding something here because I haven't actually tested this function. But logic concluded otherwise. @AmjadMasad if could elaborate on the inner working of the second ``for()`` loop and point out where I failed to see the logic behind it. I think you are on to something there but I just can't see it. I would appreciate to learn something new. – iiminov Mar 23 '16 at 09:07
  • I noticed an issue with this. If I'm trying to redirect to a slug, e.g.: `window.location.href = 'login'`, it returns false, while it should return true. I added a condition just before the first loop: `myhost.length === 1 return true` to solve it. Basically, if its a malformed url / localized domain it should stay at the current domain. Doesn't make much sense to work with malformed localized domains anyhow. You also have a small reference error in the second loop, `!= host[i]` instead of `!= myhost[i]`. – adi518 May 14 '16 at 21:37
2

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.

user113716
  • 318,772
  • 63
  • 451
  • 440
1

Well, window.location is the more standard way, so I'd suggest that over document.domain. IndexOf will match substrings, which probably isn't what you want. Why not just:

window.location.hostname == "stackoverflow.com"?

I guess for some sites you may have an optional subdomain. Like www.domain.com and just domain.com both going to the same place. If that's a concern you could make some ugly regex, or you could just split on dots:

var domainParts = window.location.hostname.split(".");
domainParts[domainParts.length - 2] == "stackoverflow"

I don't think case matters, at least in the browsers I tried (Firefox and Chrome) they normalize the domain name to lowercase automatically.

jpsimons
  • 27,382
  • 3
  • 35
  • 45
  • I see what you're saying, but why use an ugly regex when I could just use indexOf() != -1 to see if the string is a substring of the entire domain/subdomain? – Shafique Jan 06 '11 at 15:52