Sikau

Web essentials · Day 2 · about 25 min

URLs and query strings

Read and build web addresses safely.

Every part has a job

https://shop.example:443/search?q=momo&page=2#reviews — that's a protocol, a host, a port, a path, a query and a fragment. JavaScript's URL tools read and build addresses without fiddly string-joining (and without bugs like a missing &).

URL and URLSearchParams

const url = new URL("https://shop.example/search?q=momo&page=2#reviews");
console.log(url.protocol, url.hostname, url.pathname);
console.log(url.searchParams.get("q"), url.searchParams.get("page"));
console.log(url.hash);

const next = new URL("/search", "https://shop.example");
next.searchParams.set("q", "dal bhat & chiya");
next.searchParams.set("page", "1");
console.log(next.toString());

The rest of this lesson

  • Encoding: why special characters matterexplain
  • Relative URLs and the fragmentexplain
  • What's the hash?predict
  • Resolving a pathpredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 16 lessons of Web essentials