Get hostname from url


I wrote a function that will get the hostname without top level domain and it contains http or https with www as well. my problem is how to get the domain name when there is no http or https or www?

function domainName(url){

    url = (new URL(url));
    url = url.hostname.replace('www.','');
    url = url.split('.')[0];
    return url

this will work for: --- outcome is google

but will not work for: --- no outcome

console.log( Uncaught TypeError: URL constructor: is not a valid URL. )

The function you provided uses the URL constructor to parse its parameter and get the hostname. However, the URL constructor doesn’t handle URLs that don’t have a protocol (i.e., “http:” or “https:”). Therefore, if you give it something like, it’s going to fail.

Here’s a version of your function that will work even if the URL lacks the protocol or “www”.

function getDomainName(inputUrl){
  let url = inputUrl;
  if (!url.includes('://')) {
      url = 'http://' + url;
  let hostName = (new URL(url)).hostname;
  hostName = hostName.replace('www.','');
  const domain = hostName.split('.')[0];
  return domain;

Here we are checking if the url string contains “://” to identify if it has a protocol, if not, “http://” is added to the beginning of it to make sure the URL constructor can parse it correctly.

console.log(getDomainName(''));  // google
console.log(getDomainName(''));  // google
console.log(getDomainName(''));  // google

And while this works, it’s still not wonderful as there are edge cases to consider. For example https://localhost is a valid URL, as is

console.log(getDomainName(''));  // 10

If this is something public-facing that needs to handle such edge cases, you might be better off going for a library, such as parse-url.



Are you taking a URL string as input, or just trying to read the current URL?

current URL is just window.location.hostname
If you’re taking a string as input… sanitize the input?

A missing www is not your only failstate. is a valid URL; your code would tell me that this host is “ivegotasubdomain”.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.