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

JavascriptDomain Name

Javascript Problem Overview


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

document.write(document.location)

on JSFiddle it returns

> http://fiddle.jshell.net/_display/

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

Javascript Solutions


Solution 1 - Javascript

How about:

window.location.hostname

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

Solution 2 - Javascript

Let's suppose you have this url path:

http://localhost:4200/landing?query=1#2

So, you can serve yourself by the location values, as follow:

window.location.hash: "#2"window.location.host: "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:"

window.location.search: "?query=1"

Now we can conclude you're looking for:

window.location.hostname

Solution 3 - Javascript

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

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

Solution 4 - Javascript

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;
}

Examples

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 - Javascript

You can get it from location object in Javascript easily:

For example URL of this page is:

http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc

Then we can get the exact domain with following properties of location object:

location.host = "www.stackoverflow.com"
location.protocol= "http:"

you can make the full domain with:

location.protocol + "//" + location.host

Which in this example returns http://www.stackoverflow.com

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

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

Solution 6 - Javascript

If you wish a full domain origin, you can use this:

document.location.origin

And if you wish to get only the domain, use can you just this:

document.location.hostname

But you have other options, take a look at the properties in:

document.location

Solution 7 - Javascript

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;
}

http://jsfiddle.net/5U366/4/

Solution 8 - Javascript

Since this question asks for domain name, not host name, a correct answer should be

window.location.hostname.split('.').slice(-2).join('.')

This works for host names like www.example.com too.

Solution 9 - Javascript

Use

document.write(document.location.hostname)​

window.location has a bunch of properties. See here for a list of them.

Solution 10 - Javascript

window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.

There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:

let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);

Solution 11 - Javascript

If you want to get domain name in JavaScript, just use the following code:

var domain_name = document.location.hostname;
alert(domain_name);

If you need to web page URL path so you can access web URL path use this example:

var url = document.URL;
alert(url);

Solution 12 - Javascript

What about this function?

window.location.hostname.match(/\w*\.\w*$/gi)[0]

This will match only the domain name regardless if its a subdomain or a main domain

Solution 13 - Javascript

I figure it ought to be as simple as this:

url.split("/")[2]

Solution 14 - Javascript

for my case the best match is window.location.origin

Solution 15 - Javascript

Combining a few answers from the above, the following works really well for me for destroying Cookies:

  /**
   * Utility method to obtain the domain URI:
   */
  fetchDomainURI() {
    if (window.location.port.length > 0) {
      return window.location.hostname;
    }
    return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
  }

Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.

Solution 16 - Javascript

I'm new to JavaScript, but cant you just use: document.domain ?

Example:

<p id="ourdomain"></p>

<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>

Output:

domain.com

or

www.domain.com

Depending on what you use on your website.

Solution 17 - Javascript

Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname). For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.

location.hostname.split('.').filter(( _, i) => i < 2).join('.')

Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.

Solution 18 - Javascript

https://publicsuffix.org/list/

(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)

is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.

You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts

getDomainWithoutSuffix('google.com');        // returns `google`
getDomainWithoutSuffix('fr.google.com');     // returns `google`
getDomainWithoutSuffix('fr.google.google');  // returns `google`
getDomainWithoutSuffix('foo.google.co.uk');  // returns `google`
getDomainWithoutSuffix('t.co');              // returns `t`
getDomainWithoutSuffix('fr.t.co');           // returns `t`
getDomainWithoutSuffix('https://user:[email protected]:8080/some/path?and&query#hash'); // returns `example`

Solution 19 - Javascript

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFreesn&#246;wView Question on Stackoverflow
Solution 1 - JavascriptGarethView Answer on Stackoverflow
Solution 2 - JavascriptSunil ShakyaView Answer on Stackoverflow
Solution 3 - JavascriptcprcrackView Answer on Stackoverflow
Solution 4 - JavascriptadelindevView Answer on Stackoverflow
Solution 5 - JavascriptIman SedighiView Answer on Stackoverflow
Solution 6 - JavascriptRicardo FrançaView Answer on Stackoverflow
Solution 7 - JavascriptdmckView Answer on Stackoverflow
Solution 8 - JavascriptEthanView Answer on Stackoverflow
Solution 9 - JavascriptDancrumbView Answer on Stackoverflow
Solution 10 - JavascriptDaniel WintersteinView Answer on Stackoverflow
Solution 11 - JavascriptujjalView Answer on Stackoverflow
Solution 12 - Javascriptunixdebian11View Answer on Stackoverflow
Solution 13 - JavascriptAlexandru MihalceaView Answer on Stackoverflow
Solution 14 - JavascriptPavel PoberezhnyiView Answer on Stackoverflow
Solution 15 - JavascriptMicheal J. RobertsView Answer on Stackoverflow
Solution 16 - JavascriptUnluckyLukeView Answer on Stackoverflow
Solution 17 - JavascriptLucaView Answer on Stackoverflow
Solution 18 - JavascriptedelwaterView Answer on Stackoverflow
Solution 19 - JavascriptJean G.TView Answer on Stackoverflow