Get domain from URL in JavaScript
While working on a React component for my website, I have had a need to get a domain name from URL string.
Thankfully, modern browsers provide URL API which makes it very easy to read and manipulate URL without the need of using REGEX.
const url = "https://themesharbor.com/downloads/aquene/";
let domain = new URL(url);
domain = domain.hostname;
console.log(domain); //themesharbor.com
There are cases when URL can contain "www" in a domain name.
If you need to extract domain without "www" then it can be done using the replace()
method.
const url = "https://www.themesharbor.com/downloads/aquene/";
let domain = new URL(url);
domain = domain.hostname.replace('www.','');
console.log(domain); // themesharbor.com