Search code examples
javascriptsubdomain

Detect host of in a url with a subdomain


if there are a bunch of URL's:

  • sub1.sub.example.com

  • sub2.sub.example.com

  • sub3.sub.example.com

  • sub4.sub.example.com

  • etc.

How can I detect if the hostname is something.sub.example.com?

What I tried, which does not work:

if (window.location.hostname == "*.sub.example.com") {
  //actions 
}

Solution

  • I believe that you can use String#endsWith to do exactly what you want:

    if (window.location.hostname.endswith(".sub.example.com")) { . . . }
    

    As pointed out by Jake Holzinger in the comments, IE does not support String#endsWith. A simple regex solution which would have better compatibility would

    // This is a Regular Expression literal meaning
    // a string ending with ".sub.example.com" (case-insensitive)
    var regexSubdomainPattern = /\.sub\.example\.com$/ig;
    if (regexSubdomainPattern.test(window.location.hostname)) { . . . }