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.
Definition and UsageThe domain property returns the domain name of the server (the document was loaded from). The domain property returns null if the document was created in memory.
Simply put, a domain name (or just "domain") is the name of a website. It's what comes after "@" in an email address, or after "www." in a web address. If someone asks how to find you online, what you tell them is usually your domain name.
First let's create a string with our URL (Note: If the URL isn't correctly structured you'll get an error). const url = 'https://www.michaelburrows.xyz/blog?search=hello&world'; Next we create a URL object using the new URL() constructor. let domain = (new URL(url));
To access the domain name from an above URL, we can use the window. location object that contains a hostname property which is holding the domain name. Similarly, we can also use the document. domain property to access it.
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
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.
Or if you would prefer to use a regex with the test()
method, you can use:
/(^|\.)stackexchange\.com$/.test(location.hostname)
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With