Към основното съдържание
← ⚡ JavaScript & the browser·Модул C9 · Урок 4
ЗадачаParse '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
Теория

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.

🔒

Регистрирай се за да започнеш да кодираш

Теорията е отворена за всички. Редакторът, живият преглед и проверката се отключват с 7-дневен безплатен пробен период — нужна е карта.

Регистрация — безплатен пробен период →

Първите 10 урока във всеки път са безплатни. Без карта.

← НазадСледващ урок →

Един съвет за Python или уеб на ден — на имейл

Кратко, ръчно написано, без спам. Отписване с едно кликване.