JavaScript
Intermediate
Browser APIs
· 6 min read
The URL Class
Lesson 38 of 38 in the JavaScript learning path.
How do I build a lesson URL without string concatenation?
The URL class parses and builds absolute URLs. searchParams sets query keys.
Concatenating query strings forgets encoding. A title with a space or an ampersand breaks the link.
Syntax & Parameters
const url = new URL("/lessons", "https://uptoolify.com");
Example
Interactive preview availableconst base = "https://uptoolify.com";
const url = new URL("/lessons", base);
url.searchParams.set("track", "php");
url.searchParams.set("q", "route model");
const label = document.querySelector("#out");
label.textContent = url.pathname + url.search;
let bad = "ok";
try {
new URL("/lessons");
bad = "accepted";
} catch (error) {
bad = error.name;
}
label.textContent += " | " + bad;
Expected Output
/lessons?track=php&q=route+model | TypeError
Line-by-Line Walkthrough
- The base is an absolute origin.
- The path is resolved against that base.
- searchParams.set encodes the values.
- A space in the query becomes a plus or a percent sequence.
- pathname plus search is what the label shows.
- new URL with only a path throws, because there is no base.
- The catch records the error name.
- Do not pass a user string as the base. Fix the origin in your code.
Common Pitfalls & Security
Check this before you copy it.
- A relative URL without a base throws TypeError.
- Letting a user supply the base can send later requests to another origin.
- searchParams.set replaces a key. append adds another.
- url.href includes the origin. Do not log full signed URLs.
Best Practices & Modern Standards
Build links with URL and searchParams.
Keep the origin in your code. Take only the path and known query keys from the user.
Real-World Use
The catalog builds a filter link for php and the words route model without hand-encoding the space.
Frequently Asked Questions
Why did new URL throw?
The argument was relative and you did not pass a base.
How do I read one query key?
url.searchParams.get("track").
Does set encode?
Yes. Spaces and ampersands are encoded.
Can I change the path?
Assign url.pathname. Keep it a path on your origin.