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 10 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.