3

For example, I want extract only "google" from these mention hostnames

I don't want to retrieve host name, I just need the domain name without tld and subdomain(if it is there).

etc.

shekhardtu
  • 4,335
  • 7
  • 27
  • 34
  • 4
    Possible duplicate of [Get The Current Domain Name With Javascript (Not the path, etc.)](http://stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc) – DudeOfAwesome Apr 10 '17 at 21:02
  • `location.host` – dandavis Apr 10 '17 at 21:02
  • Hey Thanks @dandavis for replying so promptly but I don't want to retrieve host, I just need domain name irrespective of any subdomain or tld. – shekhardtu Apr 10 '17 at 21:09

2 Answers2

2

Well simply using location.host and extract the wanted part from it, this is a utility function that you can use:

function extractDomainName(hostname) {
    var host = hostname;
    host = host.replace(/^www\./i, "");
    host = host.replace(/(\.[a-z]{2,3})*\.[a-z]{2,3}$/i, "");
    return host;
}

It takes the whole hostname and returns only the domain name from it using .replace() method with regex to extract only the domain name.

You can see it workinh here.

Demo:

function extractDomainName(hostname) {
  var host = hostname;
  host = host.replace(/^www\./i, "");
  host = host.replace(/(\.[a-z]{2,3})*\.[a-z]{2,3}$/i, "");
  return host;
}

var tests = ["www.google.com", "www.tutorialspoint.com", "somesite.gov.fr", "www.path.co.ltd"];

tests.forEach(function(hostname) {
  console.log(hostname);
  console.log(extractDomainName(hostname));
});
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
  • Thanks @chsdk but I need only domain name, not host. for example: stackoverflow.com ==> stackoverflow – shekhardtu Apr 10 '17 at 21:11
  • I don't get it, can you please explain it. – cнŝdk Apr 10 '17 at 21:14
  • I mean for the host www.stackoverflow.com solution should return only "stackoverflow" and similarly for the www.stackoverflow.co.in solution should return only "stackoverflow" only. – shekhardtu Apr 10 '17 at 21:19
  • @shekhardtu You need to use `regex` and `string.replace()`to achieve it, please take a look at my Edit. – cнŝdk Apr 10 '17 at 21:39
  • problem with these sort of filters as that you can't tell what dots to keep: `extractDomainName("secure.payments.google.co.uk")` – dandavis Apr 10 '17 at 22:28
  • @dandavis it will give you `secure.payments.google` as expected. :) – cнŝdk Apr 10 '17 at 22:34
1

Using the hostname of the location object, you can check for the domain name before the TLD. This will ignore subdomains as well.

var domain = window.location.hostname.match(/([a-z0-9-]*?)\.[a-z]{2,}$/)[1];

console.log(domain);
KevBot
  • 17,900
  • 5
  • 50
  • 68