Parse a Basic URL into Components
Learn how to break down a standard URL into its components: protocol, hostname, pathname, query string, and hash fragment. Understand the anatomy of every URL.
Detailed Explanation
Anatomy of a URL
Every URL follows a standard structure defined by RFC 3986. Understanding this structure is fundamental for web development, API integration, and debugging network requests.
The URL Structure
https://www.example.com:443/path/to/page?key=value&foo=bar#section
\___/ \_____________/\__/\_____________/\_________________/\_______/
| | | | | |
protocol hostname port pathname query string hash
Component Breakdown
Protocol (
https:) — The scheme that tells the browser how to communicate. Common protocols includehttp:,https:,ftp:, andfile:.Hostname (
www.example.com) — The domain name or IP address of the server. This is resolved via DNS to find the server's actual IP address.Port (
:443) — The network port. Default ports (80 for HTTP, 443 for HTTPS) are typically omitted from the URL but are always used behind the scenes.Pathname (
/path/to/page) — The path to the specific resource on the server. In modern web frameworks this is often a route rather than a file path.Query String (
?key=value&foo=bar) — Key-value pairs separated by&that pass data to the server. The query string begins with?.Hash / Fragment (
#section) — A client-side reference to a section within the page. The hash is never sent to the server.
Browser URL API
The browser provides a built-in URL class for parsing:
const url = new URL("https://example.com/path?q=test#top");
console.log(url.protocol); // "https:"
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.search); // "?q=test"
console.log(url.hash); // "#top"
This API handles edge cases like punycode domains, IPv6 addresses, and percent-encoded characters automatically.
Use Case
URL parsing is a daily task for web developers. Whether you are extracting query parameters from a callback URL, debugging a broken redirect, or building a link dynamically in JavaScript, understanding how each URL component works is essential. This knowledge is the foundation for working with routing, APIs, and web security.