Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 11.4 — URL, URLSearchParams and location
JavaScript · Example 2 of 3

URLSearchParams: build, read and encode

Object.fromEntries keeps only the last tag, so use getAll for repeated keys. In the unencoded URL, the server would read q as tea and see a second, empty parameter called coffee.

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.

01

Write getPage(urlText) that returns the page query parameter as a number, or 1 when it's missing or not a positive whole number.

02

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

01

Name the parts of a URL and what each is used for.

02

Why use URL/URLSearchParams instead of string concatenation and split?

03

What is the difference between location.assign, location.replace and setting location.hash?

04

How does new URL(relative, base) resolve ../a, ?x=1, #y and //host/z?

URLSearchParams: build, read and encode

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

q=tea+%26+coffee&sort=price&tag=hot&tag=new
tea & coffee [ 'hot', 'new' ] null 4
{ q: 'tea & coffee', sort: 'price', tag: 'new' }
q=tea+%26+coffee&sort=price&page=2
/search?q=tea & coffee
/search?q=tea%20%26%20coffee
https://shop.example.com/search?q=tea+%26+coffee&sort=rating