URL parsing and relative URL resolution
Quick answer
The URL interface parses and resolves URLs. Use a base URL to resolve a relative path and inspect fields rather than splitting strings manually.
How it works
new URL(input, base) accepts absolute input or relative input with a valid base. pathname is the path; search includes the query prefix; hash includes the fragment prefix. origin identifies scheme, host and port for ordinary HTTP(S) URLs. A leading slash resolves relative to the origin root, while a relative segment resolves against the base directory. Invalid input can throw TypeError.
Local examples
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const u=new URL("item/2","https://example.test/api/");console.log(u.href,u.pathname);})()Expected console output:
https://example.test/api/item/2 /api/item/2The trailing slash makes api a directory.
Run in a fresh browser document; no external network is needed. The actual ByteMind editor is unverified.
(async () => {const u=new URL("/items?q=pen#top","https://example.test/api/");console.log(u.pathname,u.search,u.hash);})()Expected console output:
/items ?q=pen #topA leading slash starts at the origin root.
Common mistakes
URL parsing does not make a destination safe or authorized. Validate protocol and destination against your policy.
Guided practice
Resolve item/2 against bases ending in /api and /api/ and compare.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
URL parsing and relative URL resolution — Knowledge Check
Apply the concept and reason about the example output.
What does new URL require for relative input?
Which property exposes the path without query?
Does successful URL parsing authorize a destination?
What is the expected console output of URL parsing and relative URL resolution example 1?
(async () => {const u=new URL("item/2","https://example.test/api/");console.log(u.href,u.pathname);})()What is the expected console output of URL parsing and relative URL resolution example 2?
(async () => {const u=new URL("/items?q=pen#top","https://example.test/api/");console.log(u.pathname,u.search,u.hash);})()