Javascript get domain from url without subdomain refers to extracting the main domain name part from an URL, excluding all subdomains. This approach is useful in various cases, like log parsing, zone-based data analysis, security filtering, or just to display a simplified URL on the front end. Now let’s investigate how to extract the primary domain name from a URL that excludes subdomains.
Table of Contents
URL Components That We Need to Consider:
Before starting coding, it’s vital to know every possible corner case of extracting the main domain name from the URL. Start with the basic components of a URL first.
- Protocol: The scheme used (e.g., http, https).
- Subdomain: Optional prefix like www, blog, or any other.
- Domain: The main part, such as example.com.
- Top-Level Domain (TLD): The suffix like .com, .org, etc.
- Path: The specific resource location within the domain.
Consider the URL https://blog.example.com/path. Here, our goal is to extract example.com from the given URL.
JavaScript Get Domain from URL without Subdomain: Extracting the Main Domain Name
To collect the main domain name without subdomains, we can use the JS in-built URL interface along with some string manipulation methods.
Using URL Interface
The JS in-built URL interface provides us with a straightforward way to parse and manipulate URLs, like below:
function getDomainWithoutSubdomain(url) {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname;
const parts = hostname.split('.');
// Extract main domain and TLD
if (parts.length > 2) {
return parts.slice(parts.length - 2).join('.');
}
return hostname;
}
// Example usage
// javascript get domain from url without subdomain
const url = 'https://blog.example.com/path';
console.log(getDomainWithoutSubdomain(url));
// Output: example.com
Code Explanation
In this approach:
- Parse the URL: Create a new URL object to break down the URL into its components.
- Extract Hostname: Get the hostname (e.g., blog.example.com).
- Split Hostname: Split the hostname by the dot (.) character.
- Remove Subdomains: Use array slicing to get the last two elements, which represent the domain and TLD.
Handling Corner Cases
It’s necessary to check all possible corner cases, such as URLs without subdomains or different TLD structures.
function getDomainWithoutSubdomain(url) {
try {
const parsedUrl = new URL(url);
const hostname = parsedUrl.hostname;
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error('Invalid domain');
}
if (parts.length === 2) {
return hostname; // No subdomain present
}
return parts.slice(parts.length - 2).join('.');
} catch (e) {
console.error('Invalid URL', e);
return null;
}
}
// Example usage
// javascript get domain from url without subdomain
console.log(getDomainWithoutSubdomain('https://example.com')); // Output: example.com
console.log(getDomainWithoutSubdomain('https://www.example.co.uk'));
// Output: example.co.uk
Code Explanation
This modified code is able to do:
- Error Handling: Use the try-catch block to manage invalid URLs.
- Subdomain Check: Check the length of the hostname parts to determine if subdomains exist.
Some Practical Use Cases
Analytics: Extracting the main domain helped us to create structured data across subdomains for analytics purposes.
Security Filtering: Simplifying URLs to their main domain can aid in setting security policies or filters.
Display Simplification: For user interfaces, displaying the main domain without subdomains can make URLs more readable and less cluttered.
Conclusion
javascript get domain from url without subdomain is a common task that can be easily done by using the URL interface and some basic JS string manipulation. So it’s possible to get the main domain name from a URL without a subdomain by using our knowledge of URL structure and the right logic.
Our second method shows how you can handle different URL formats and corner cases. But still, there are some cases where, when creating a generic application, you may need more sophisticated logic based on standard domain extension names like.co.uk, etc. So keep this in mind before using any custom logic.
๐๏ธโโ๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐ฅ Asp.net C# Developer
๐ Solution Architect
๐จโโ๏ธ Database Administrator
๐ข Speaker
๐ MCTS since 2009
Leave a Reply