Skip to main content
JavaScript & the browser·Module C9 · Lesson 4
TaskParse '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
Theory

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.

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 15 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.