Zum Hauptinhalt springen
← ⚡ JavaScript & the browser·Modul C9 · Lektion 4
AufgabeParse 'https://learnpython.academy/courses/foundations?ref=hn&sort=new'. Log hostname, pathname, searchParams.get('ref'). Then add tag=python and tag=tutorial, delete ref, log the final url.toString().

URL + URLSearchParams

100 XP7 min
Theorie

Parse and build URLs without regex

The built-in URL class handles every edge case:

const u = new URL("https://learnpython.academy/courses/foundations?ref=hn&sort=new");

u.hostname;   // "learnpython.academy"
u.pathname;   // "/courses/foundations"
u.searchParams.get("ref");  // "hn"
u.searchParams.get("sort"); // "new"
u.searchParams.has("page"); // false

Building a URL

searchParams is mutable — set, append, delete:

u.searchParams.set("sort", "top");
u.searchParams.delete("ref");
u.searchParams.append("tag", "python");
u.searchParams.append("tag", "tutorial");
u.toString();
// "https://learnpython.academy/courses/foundations?sort=top&tag=python&tag=tutorial"

Why this beats string-splitting

Encoding is handled automatically. Anna K. becomes Anna%20K.. Regex-based query parsers always miss an edge case eventually.

Relative URLs

new URL("page?x=1", "https://site.com/dir/") resolves against the base — that's how href resolution works in the spec.

🔒

Anmelden, um zu programmieren

Theorie ist für alle offen. Editor, Live-Preview und Check werden mit 7-Tage-Gratis-Test freigeschaltet — Karte erforderlich, jederzeit kündbar.

Registrieren — Gratis-Test →

Die ersten 10 Lektionen jedes Tracks sind kostenlos. Keine Karte nötig.

← ZurückNächste Lektion →

Bekomme einen Python- oder Web-Tipp pro Tag — per E-Mail

Kurz, handgeschrieben, kein Spam. Abmelden mit einem Klick.