JAVASCRIPT
Extract Domain Name from URL String
Easily extract the clean domain name (e.g., example.com) from any given URL string, removing protocols, subdomains, paths, and query parameters using regex.
const url = "https://www.blog.example.com:8080/path/to/page?query=test#hash";
const domainRegex = /^(?:https?:\/\/)?(?:[^@
]+@)?(?:www\.)?([^:\/
?#]+)/i;
const match = url.match(domainRegex);
const domain = match ? match[1] : null;
console.log(domain); // Output: blog.example.com
const url2 = "http://user:[email protected]";
const match2 = url2.match(domainRegex);
console.log(match2 ? match2[1] : null); // Output: my-site.net
const url3 = "ftp://another.domain"; // Does not match (only http/https protocols considered)
const match3 = url3.match(domainRegex);
console.log(match3 ? match3[1] : null); // Output: null
How it works: This regex extracts the main domain and subdomain (if present) from a URL. It optionally matches the protocol `(?:https?:\/\/)?`, user credentials `(?:[^@
]+@)?`, and 'www.' prefix `(?:www\.)?` using non-capturing groups. The key part is the capturing group `([^:\/
?#]+)` which matches any characters that are not a colon, slash, newline, question mark, or hash, effectively capturing the domain part before any port, path, or query parameters. The `i` flag makes it case-insensitive.