Get The Current Domain Name With Javascript (Not the path, etc.)


Get The Current Domain Name With Javascript (Not the path, etc.)

I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to detect the actual domain name that the page is loading from so that I know what to change my content to?
I’ve looked around for stuff like this but most of it doesn’t work the way I want it to.
For instance when using

on JSFiddle it returns

i.e. the actual path or whatever that is.


Solution 1:

How about:


The location object actually has a number of attributes referring to different parts of the URL

Solution 2:

If you are not interested in the host name (for example but in the domain name (for example, this works for valid host names:

function getDomainName(hostName)
    return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);

Solution 3:

Try to run in script :
path: http://localhost:4200/landing?query=1#2


Location have following values:

window.location.hash: "#2"
​ "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:" "?query=1"

Solution 4:

function getDomain(url, subdomain) {
    subdomain = subdomain || false;

    url = url.replace(/(https?:\/\/)?(www.)?/i, '');

    if (!subdomain) {
        url = url.split('.');

        url = url.slice(url.length - 2).join('.');

    if (url.indexOf('/') !== -1) {
        return url.split('/')[0];

    return url;


Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the ‘main domain’

Solution 5:

You can get it from location object in Javascript easily:

For example URL of this page is:

Then we can get the exact domain with following properties of location object: = ""
location.protocol= "http:"

you can make the full domain with:

location.protocol + "//" +

Which in this example returns

I addition of this we can get full URL and also the path with other properties of location object:

location.href= ""    
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"

Solution 6:

If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.

The following code does this:

var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;

if (isSubdomain) {
    domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
else {
  domain = window.location.hostname;