JAVASCRIPT

Extract Root Domain from a URL

Extract the core domain name (e.g., example.com) from a full URL string, ignoring scheme, www subdomain, path, and query parameters.

const url = "https://www.example.com/path/to/page?id=123";
const regex = /(?:https?:\/\/)?(?:www\.)?([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})/; // Catches example.com
const match = url.match(regex);

if (match && match[1]) {
    console.log(match[1]); // "example.com"
} else {
    console.log("No domain found.");
}
How it works: This regex uses non-capturing groups `(?:...)` for optional `http(s)://` and `www.`. The key part is the capturing group `([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})` which matches one or more alphanumeric characters, dots, or hyphens, followed by a dot and at least two letters for the top-level domain. This effectively isolates the root domain from the URL.

Need help integrating this into your project?

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

Hire DigitalCodeLabs