Complete Guide to Extracting Protocol, Domain and Port from URL in JavaScript

Nov 17, 2025 · Programming · 12 views · 7.8

Keywords: JavaScript | URL Parsing | Protocol Domain Port | String Splitting | Browser Compatibility

Abstract: This article provides a comprehensive exploration of multiple methods for extracting protocol, domain, and port from URLs in JavaScript. It focuses on the classical string splitting approach while comparing modern solutions like URL API and DOM parsers. Through complete code examples and in-depth technical analysis, the article helps developers understand the applicable scenarios, performance characteristics, and browser compatibility of different methods, offering comprehensive reference for URL processing in web development.

Fundamental Concepts of URL Parsing

In web development, URL (Uniform Resource Locator) serves as the foundation for accessing network resources. A standard URL typically consists of multiple components: protocol, domain, port, path, and query parameters. Among these, protocol, domain, and port form the fundamental architectural parts of a URL, crucial for constructing complete network requests.

Classical String Splitting Method

For scenarios requiring compatibility with older browsers, the string splitting method offers the broadest compatibility. The core idea of this approach is to split the URL string using specific delimiters and then extract the required components.

// Get the complete URL of the current page
var url = window.location.href;

// Split URL using forward slash as delimiter
var arr = url.split("/");

// Combine protocol, domain, and port
var result = arr[0] + "//" + arr[2];

This method works based on the standard URL format: protocol followed by "://", then domain and port. By splitting the URL by "/", the first element of the array (arr[0]) contains the protocol and ":", while the second element (arr[2]) contains the domain and port (if present).

Method Advantages and Limitations Analysis

The primary advantage of the string splitting method lies in its excellent browser compatibility. Since it doesn't rely on any modern browser APIs, this method can work in virtually all browsers, including IE6. Additionally, the code logic is simple and intuitive, easy to understand and maintain.

However, this method also has some limitations. First, it assumes the URL follows standard format; if the URL format is abnormal, it may lead to parsing errors. Second, when the port number is absent, arr[2] may only contain the domain, requiring additional logic to handle this situation. Finally, this method cannot gracefully handle URL encoding and special characters.

Comparison of Modern URL Parsing Solutions

URL API Method

Modern browsers provide native URL API that can parse URLs more elegantly:

const url = new URL('https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer');
const protocol = url.protocol;  // 'https:'
const domain = url.hostname;    // 'localhost'
const port = url.port;          // '8181'
const fullResult = url.protocol + '//' + url.host;  // 'https://localhost:8181'

The URL API provides more precise URL parsing, automatically handling various edge cases such as default ports, IPv6 addresses, etc. However, it's important to note that IE11 and earlier versions do not support this API.

DOM Parser Method

For scenarios requiring compatibility with older browsers while desiring more reliable parsing, the DOM parser can be used:

// Create anchor element but don't add to document
const url = document.createElement('a');
url.setAttribute('href', 'https://localhost:8181/ContactUs-1.0/contact?lang=it&report_type=consumer');

// Browser automatically parses the URL
const protocol = url.protocol;  // 'https:'
const domain = url.hostname;    // 'localhost'
const port = url.port;          // '8181'

This method leverages the browser's built-in URL parsing capabilities, providing more reliability than manual string splitting while maintaining good browser compatibility.

Performance and Compatibility Considerations

When choosing a URL parsing method, it's essential to comprehensively consider performance, compatibility, and code maintainability. The string splitting method, while offering the best performance, has poorer robustness; the URL API method is the most modern and feature-complete but has limited compatibility; the DOM parser method strikes a good balance between compatibility and reliability.

For modern web applications, it's recommended to prioritize using the URL API and provide fallback solutions through feature detection:

function parseURL(urlString) {
    if (typeof URL === 'function') {
        // Use modern URL API
        const url = new URL(urlString);
        return {
            protocol: url.protocol,
            domain: url.hostname,
            port: url.port,
            full: url.protocol + '//' + url.host
        };
    } else {
        // Fallback to string splitting method
        const arr = urlString.split("/");
        return {
            full: arr[0] + "//" + arr[2]
        };
    }
}

Practical Application Scenarios

URL parsing has wide-ranging applications in web development. When building API requests, it's necessary to extract base paths from the current page URL; when implementing routing systems for single-page applications, URL paths and parameters need to be parsed; when constructing micro-frontend architectures, base addresses for sub-applications need to be extracted from the main application URL.

Regardless of the method chosen, understanding URL structure and parsing principles is a fundamental skill for web developers. By selecting appropriate methods, developers can build URL processing logic that is both efficient and robust.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.