URLs have genuine structural complexity that manual string manipulation reliably mishandles on edge cases. The native URL and URLSearchParams objects implement the actual URL specification correctly, for free.
1Structured, Correct URL Parsing
new URL(urlString) parses a URL string into a structured object exposing distinct, individually correct properties: .protocol ("https:"), .hostname ("example.com"), .pathname ("/search"), .search ("?q=shoes"), .hash ("#results"), and several others.
This eliminates an entire category of fragile, error-prone manual approaches — regex patterns or naive string.split() calls that break on edge cases like URLs containing unusual characters, ports, or unexpected structures the developer didn't anticipate when writing the parsing logic.
2Correct Query String Handling With URLSearchParams
URLSearchParams (accessible via url.searchParams on a URL object, or constructed standalone with new URLSearchParams(queryString)) provides a Map-like interface — .get(), .set(), .has(), .delete(), .append() — for reading and modifying query parameters, with correct URL encoding and decoding handled automatically in both directions.
Manual query-string construction ('?q=' + userInput) is a frequent source of bugs when userInput contains characters like spaces, &, or = that require proper encoding — URLSearchParams handles this correctly by default, without requiring the developer to remember encodeURIComponent() manually.
3Resolving Relative URLs Against A Base
new URL(relativePath, baseUrl) correctly resolves a relative path against a base URL, implementing the full set of relative-resolution rules — ../ parent-directory traversal, absolute paths starting with /, protocol-relative URLs starting with // — exactly as browsers themselves resolve links.
This is genuinely non-trivial to replicate correctly with manual string concatenation, which frequently mishandles edge cases like a base URL that already has a query string, or a relative path with multiple ../ segments needing correct traversal up the path hierarchy.
4Step-by-Step Breakdown
Stop Parsing URLs With Regex. URLs have real structural complexity — protocol, host, path, query string, fragment, encoding rules — that a hand-rolled regex or string-splitting approach reliably gets wrong on edge cases. The native URL API parses and constructs URLs correctly, matching the actual URL specification.
new URL() Parses Into Structured Components. new URL('https://example.com/search?q=shoes#results') returns an object with distinct, correctly-parsed properties — .protocol, .hostname, .pathname, .search, .hash — eliminating fragile manual string splitting.
URL Object Parsing. What does new URL('https://example.com/search?q=shoes').pathname return?
- →The entire original URL string
- →"/search"
- →"example.com"
URLSearchParams Correctly Handles Query Strings. url.searchParams (or standalone new URLSearchParams(str)) provides a Map-like interface for reading, adding, and modifying query parameters, automatically handling correct encoding — a task manual string concatenation frequently gets wrong for special characters.
URLSearchParams Encoding. Why does URLSearchParams handle special characters in query values more reliably than manual string concatenation?
- →There's no real difference; both handle it equally
- →It automatically applies correct URL encoding/decoding rules
- →It simply strips out any special characters entirely
Constructing URLs From A Base. new URL(relativePath, baseUrl) resolves a relative path against a base URL correctly, handling all the edge cases of relative resolution (../ traversal, leading slashes, etc.) that manual string concatenation handles inconsistently or incorrectly.
Resolving Relative URLs. What's the benefit of using new URL(relativePath, baseUrl) instead of manually concatenating strings to build an absolute URL from a relative one?
- →It executes measurably faster than string concatenation
- →It correctly handles relative path resolution rules like ../ traversal
- →There's no real functional benefit
URL API Mastered. You now know how to parse URLs into structured components with new URL(), correctly read and build query strings with URLSearchParams, and correctly resolve relative URLs against a base — all without fragile regex or manual string manipulation.
Build A Link With Query Parameters. The URL API parses query strings — add one to this link's href.
Level Up 🚀
Advanced cheat sheets, SEO tricks, and interview prep for this topic.
Browser Support
Fully supported.
Fully supported.
Fully supported.
Fully supported.
Accessibility (A11y)
1Correctly Parsed And Constructed URLs Support Reliable, Predictable Navigation For All Users
URL-handling bugs that produce broken or malformed links affect every user's ability to navigate reliably, including assistive technology users following links via screen reader navigation.
SEO Implications
- 1
Correct URL Construction Directly Supports Reliable Canonical Tags And Internal Linking
Since canonical URLs (covered earlier in the Modern SEO module) must be exact and absolute, using the URL API to construct them programmatically avoids the encoding and resolution bugs manual string building risks.
Best Practices
Always Use The URL API Instead Of Regex Or Manual String Splitting For URL Parsing
URLs have genuine specification-level complexity that hand-rolled parsing logic reliably gets wrong on real-world edge cases the developer didn't anticipate.
Use URLSearchParams For Any Query String Construction Involving Dynamic Or User-Provided Values
It guarantees correct encoding automatically, eliminating an entire category of subtle bugs from forgetting or incorrectly applying encodeURIComponent() manually.
Frequent Bugs
A search query containing an ampersand or space breaks the resulting URL when built via manual string concatenation.
Use URLSearchParams to construct the query string, which handles correct encoding automatically.
A regex-based URL parser fails on an unusual but valid URL structure not anticipated when the regex was written.
Replace the regex parser with new URL(), which implements the full, correct URL specification rather than an approximation.
Real-World Examples
Building A Correctly Encoded Search URL
Constructing a search results URL from user input, guaranteed to handle special characters correctly.
const url = new URL('https://example.com/search');
url.searchParams.set('q', userInput);
window.location.href = url.href;