JavaScript Intermediate Browser APIs · 6 min read

The URL Class

Lesson 38 of 38 in the JavaScript learning path.

All Tutorials ❯

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

Syntax
const url = new URL("/lessons", "https://uptoolify.com");

Example

Interactive preview available
links.js
const 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

  1. The base is an absolute origin.
  2. The path is resolved against that base.
  3. searchParams.set encodes the values.
  4. A space in the query becomes a plus or a percent sequence.
  5. pathname plus search is what the label shows.
  6. new URL with only a path throws, because there is no base.
  7. The catch records the error name.
  8. 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…