Q:

Use javascript to get domain name including subdomains

I just wanted to know if there was a way to get something to be future proof, as we may create new subdomains, and want people know that the site they are using is correct (as we have had a few cases of people rehosting our site)
if(window.location.href != "example.com" || "*.example.com"){
document.getElementById('alert').innerHTML = "This is site is not recognized as an official site";}

Where "*" would be a wildcard for any subdomain, and the ID "alert" is a div which we use to display important message.

A:

Use location.hostname and check if it ends with your domain, e.g. like this:
if(!location.hostname.match(/example.com$/)){
     alert(...);
}

This will match the domain example.com as well as www.example.com and any subdomain.example.com. But it will also match things like otherexample.com. To prevent this, use the following regex:
if(!location.hostname.match(/(^|\.)example.com$/)){
     alert(...);
}

This regex matches anything which is only example.com or starts with a dot and ends with example.com, so www.example.com and subdomain.example.com, but not otherexample.com because there's not dot in front of this example.com.

