Take a URL apart
+ in a query means a space, so get("q") gives red shoes. A path alone isn't a full URL: give a base as the second argument.
The URL class splits any web address into reliable parts and resolves relative links, URLSearchParams reads and builds query strings with correct encoding, and location is the current page's URL, which you can read and change to navigate.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write getPage(urlText) that returns the page query parameter as a number, or 1 when it's missing or not a positive whole number.
Write withParams(base, obj) that returns a URL string with every key of obj added as a query parameter, skipping null and undefined values.
Explain it without notes
Name the parts of a URL and what each is used for.
Why use URL/URLSearchParams instead of string concatenation and split?
What is the difference between location.assign, location.replace and setting location.hash?
How does new URL(relative, base) resolve ../a, ?x=1, #y and //host/z?
Preview
Console
Nothing logged yet.Expected console output
protocol https:
hostname shop.example.com
port 8080
host shop.example.com:8080
origin https://shop.example.com:8080
pathname /search
search ?q=red+shoes&page=2
hash #reviews
q is red shoes
https://shop.example.com:8080/search?q=red+shoes&page=3
https://a.com/shop/img/a.png
https://a.com/list?page=2
false
TypeError: Failed to construct 'URL': Invalid URL