Прескочи на главни садржај
← ⚡ 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 или веб дневно — на имејл

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