The URL and URLSearchParams interfaces replace fragile, regex-based URL and query-string parsing with a robust, spec-compliant API built directly into the browser and Node.js.
1The URL API | JavaScript Tutorial - In-Depth Guide Part 1
The URL constructor parses a URL string into its components โ protocol, host, pathname, search, hash โ without any manual string splitting or regex.
const url = new URL('https://example.com:8080/path?query=1#hash');
url.hostname; // 'example.com'
url.pathname; // '/path'
url.hash; // '#hash'Parsing URLs
2The URL API | JavaScript Tutorial - In-Depth Guide Part 2
URLSearchParams parses and builds query strings correctly, handling encoding/decoding and repeated parameter names automatically.
const params = new URLSearchParams('?tag=js&tag=web&page=2');
params.get('page'); // '2'
params.getAll('tag'); // ['js', 'web']URLSearchParams
3The URL API | JavaScript Tutorial - In-Depth Guide Part 3
A URL object's '.searchParams' property gives direct, live access to its query string as a URLSearchParams instance โ modifying it updates the URL automatically.
const url = new URL('https://example.com/search');
url.searchParams.set('q', 'javascript tutorials');
url.href; // 'https://example.com/search?q=javascript+tutorials'Building Query Strings
4The URL API | JavaScript Tutorial - In-Depth Guide Part 4
The URL constructor's second argument resolves a relative URL against a base URL, exactly like a browser resolves a relative link on a page.
new URL('../logo.png', 'https://example.com/blog/post-1/').href;
// 'https://example.com/logo.png'Resolving Relative URLs
5The URL API | JavaScript Tutorial - In-Depth Guide Part 5
Passing an invalid URL string to the URL constructor throws a TypeError immediately, which is a reliable way to validate URL input from users.
function isValidUrl(str) {
try {
new URL(str);
return true;
} catch {
return false;
}
}Validating URLs
6Step-by-Step Breakdown
The URL constructor parses a URL string into its components โ protocol, host, pathname, search, hash โ without any manual string splitting or regex.
URLSearchParams parses and builds query strings correctly, handling encoding/decoding and repeated parameter names automatically.
Checkpoint: Does URLSearchParams correctly handle a query string with the same key appearing multiple times?
- โYes, getAll() retrieves every value for that key
- โNo, only the last occurrence is kept
A URL object's '.searchParams' property gives direct, live access to its query string as a URLSearchParams instance โ modifying it updates the URL automatically.
The URL constructor's second argument resolves a relative URL against a base URL, exactly like a browser resolves a relative link on a page.
Passing an invalid URL string to the URL constructor throws a TypeError immediately, which is a reliable way to validate URL input from users.
Checkpoint: What happens if you pass a malformed string to new URL(...)?
- โIt throws a TypeError
- โIt returns null
Next, we'll explore 'The History API'.
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)
1Reflect Accessible Filter State in the URL for Shareable, Bookmarkable Views
Using URLSearchParams to encode active filters in the URL lets keyboard and screen reader users bookmark or share a specific filtered view, and lets the page restore that exact state (including any relevant focus or announcement) on load.
SEO Implications
- 1
Clean, Correctly-Encoded URLs Are More Crawlable and Shareable
Search engines parse and index URLs; malformed query strings from manual concatenation (double-encoded characters, missing separators) can produce broken or duplicate-looking URLs that hurt crawl efficiency and canonicalization.
Best Practices
Use URL/URLSearchParams Instead of Manual String Concatenation for Query Strings
Manual concatenation is a common source of double-encoding bugs, missing "?"/"&" separators, and mishandling of special characters that URLSearchParams handles correctly by construction.
Validate User-Supplied URLs with the URL Constructor, Not a Custom Regex
A hand-written URL-validation regex is almost always incomplete or overly permissive; relying on the actual spec-compliant browser/Node parser is more robust.
Frequent Bugs
Manually building a query string with template literals, forgetting to encodeURIComponent() a value containing special characters like '&' or '#', corrupting the resulting URL.
Use URLSearchParams to build the query string instead, which handles encoding automatically and correctly for every value.
Assuming a relative URL like 'images/logo.png' can be safely string-concatenated onto a base URL, breaking when the base has its own path segments or query string.
Use `new URL(relativePath, baseUrl)` to correctly resolve the relative path according to standard URL resolution rules.
Real-World Examples
Building a Shareable Search Results URL
A search feature needed to reflect the current search query and filters in the URL, so results could be shared via a link and restored on page load.
function buildSearchUrl(baseUrl, { query, category, page }) {
const url = new URL(baseUrl);
url.searchParams.set('q', query);
if (category) url.searchParams.set('category', category);
url.searchParams.set('page', String(page));
return url.toString();
}