CodersTechZone
  • .NET
    • C#
    • ASP.Net
  • HTML
  • Javascript
  • CSS
  • Database
    • SQL Server
    • MYSql
    • Oracle
  • AI
  • TechNews
  • Web-Stories

JavaScript Get Domain from URL Without Subdomain: 3 Quick Hacks

Shawpnendu Bikash Maloroy

June 24, 2024
javascript get domain from url without subdomain - solve with custom js function
Spread the love

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:
  • JavaScript Get Domain from URL without Subdomain: Extracting the Main Domain Name
    • Using URL Interface
    • Code Explanation
    • Handling Corner Cases
    • Code Explanation
  • Some Practical Use Cases
  • Conclusion

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.
buymeacoffee

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.

Note

If you are still unable to get the main domain name due to other corner cases then it’s recommend to use the public suffix list js api.

buymeacoffee

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.

Shawpnendu Bikash Maloroy
Shawpnendu Bikash Maloroy

๐Ÿ‹๏ธโ€โ™‚๏ธ Discover Code Blocks From 20+ yrs JS Expert
๐Ÿ’ฅ Asp.net C# Developer
๐Ÿ† Solution Architect
๐Ÿ‘จโ€โœˆ๏ธ Database Administrator
๐Ÿ“ข Speaker
๐ŸŽ“ MCTS since 2009

Share this:

  • Click to share on Facebook (Opens in new window) Facebook
  • Click to share on X (Opens in new window) X

Spread the love
ยซPrevious
Nextยป

Good to Know

  • JavaScript Get Query String: Just 2 Tips You NeedJavaScript Get Query String
  • JavaScript Get Current Year: 3 Secret Techniques You Need to Know Now!JavaScript Get Current Year 3 Secret Techniques You Need to Know Now!
  • JavaScript AI Hacks: How to Use AI for Coding in 2025 ๐Ÿš€๐Ÿค–JavaScript AI Hacks: How to Use AI for Coding in 2025
  • How to Call JavaScript Function in HTML Without Onclick?How to Call JavaScript Function in HTML Without Onclick?
  • JavaScript No-Code Automation: How to Replace Zapier with a Few Lines of CodeJavaScript No-Code Automation
  • 10 JavaScript One-Liners That Will Blow Your Mind in 202510 JavaScript One-Liners That Will Blow Your Mind in 2025

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • 5 Lesser-Known JavaScript Functions
    5 Lesser-Known JavaScript Functions to Boost Your Coding Efficiency
  • 7 Weird JavaScript Tricks That Look Like Bugs
    7 Weird JavaScript Tricks That Look Like Bugs (#3 Will Shock You!)
  • Build a JavaScript Gamer Journal in 8 Lines
    ๐ŸŽฎ Build a JavaScript Gamer Journal in 8 Lines: Track Your Wins Like a Pro! ๐Ÿ†
  • JavaScript Pet Feeder Reminder in 7 Lines
    How to Code a Simple JavaScript Pet Feeder Reminder in 7 Lines: Feed Your Pet Like a Coding Boss! ๐Ÿถ
  • 10-line calculator JavaScript
    Build a Simple Calculator in JavaScript: 10 Lines to Wow Your Friends!

About-CodersTech Zone |  Contact |  Disclaimer |  Fact-Checking policy |  Affiliate Disclosure |  Privacy Policy

Copyright ยฉ 2024 CodersTechZone.com