Cover Image for How to get domain name from URL in JavaScript
140 views

How to get domain name from URL in JavaScript

To extract the domain name from a URL in JavaScript, you can use the following approach:

JavaScript
function getDomainName(url) {
  // Remove the protocol (e.g., "http://" or "https://")
  let domain = url.replace(/^(https?:\/\/)?/, '');

  // Remove everything after the first forward slash ("/")
  domain = domain.split('/')[0];

  // Remove any subdomains by keeping only the last two parts
  domain = domain.split('.').slice(-2).join('.');

  return domain;
}

// Example usage
const url = 'https://www.example.com/path/page.html';
const domain = getDomainName(url);
console.log(domain); // Output: "example.com"

In this example, the getDomainName() function takes a URL as input. It removes the protocol from the beginning of the URL using a regular expression and the replace() method. Then, it splits the URL by the forward slash (“/”) using the split() method and keeps only the first part, which represents the domain.

Next, it splits the domain by the period (“.”) using the split() method and keeps only the last two parts. This is done to remove any subdomains and obtain the top-level domain and the domain name.

Finally, it joins the last two parts of the domain with a period (“.”) using the join() method and returns the extracted domain name.

By using this approach, you can extract the domain name from a URL in JavaScript. Please note that this approach assumes the URLs provided are in standard format and may not handle all possible edge cases.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS