JAVASCRIPT

Extracting the Domain Name from a Full URL

Learn how to precisely extract the main domain (e.g., example.com, subdomain.example.com) from any given URL string, useful for analytics or content aggregation.

const url = "https://www.subdomain.example.com/path/to/page?query=test";
const domainRegex = /^(?:https?:\/\/)?(?:www\.)?([^\/]+)\/?.*/i;
const match = url.match(domainRegex);
console.log(match ? match[1] : null); // Output: "subdomain.example.com"

const shortUrl = "http://anothersite.net";
const shortMatch = shortUrl.match(domainRegex);
console.log(shortMatch ? shortMatch[1] : null); // Output: "anothersite.net"

const noProtocolUrl = "my-site.org/page";
const noProtocolMatch = noProtocolUrl.match(domainRegex);
console.log(noProtocolMatch ? noProtocolMatch[1] : null); // Output: "my-site.org"
How it works: This JavaScript snippet extracts the domain name from a URL. The regex `^(?:https?:\/\/)?(?:www\.)?([^\/]+)\/?.*/i` breaks down as follows: `^(?:https?:\/\/)?` optionally matches `http://` or `https://`. `(?:www\.)?` optionally matches `www.`. `([^\/]+)` is the crucial capturing group that matches one or more characters that are NOT a slash, stopping at the first path segment. `\/?.*` matches the rest of the URL. The `i` flag provides case-insensitive matching.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs