JavaScript lesson · 18 min

JavaScript URLSearchParams

Read, update, and generate query strings with URLSearchParams.

Code runs locally in your browser

What you will practice

  • Read values from a query string.
  • Update query parameters safely.
  • Generate a new URL with encoded parameters.

What this means

A query string is the part of a URL after the question mark. It often stores filters, search terms, page numbers, tracking tags, or settings.

`URLSearchParams` is a browser API that helps read and write query parameters without manually splitting strings.

It also handles URL encoding, so spaces and special characters become safe inside a URL.

If this is your first time seeing this

Query parameters are small pieces of state inside a URL.

URLSearchParams helps you read and change them without manually cutting strings apart.

Mini glossary

Query string
The part of a URL after `?`.
Parameter
A key-value pair inside a query string.
Encoding
Converting unsafe URL characters into a safe URL form.

Example from everyday life

URLSearchParams is like a labeled control panel for a URL. Instead of cutting wires by hand, you turn the labeled knobs: query, page, source, campaign.

How it works step by step

  1. The code creates a URL object from a full URL.
  2. `url.searchParams.get("q")` reads the search query.
  3. `set` updates the page number and adds a new source parameter.
  4. `url.toString()` prints the updated URL with encoded values.

Where you will use this

  • A search page stores the current query in the URL.
  • A product list stores category and page filters in query parameters.
  • A marketing link builder adds UTM parameters safely.

Before you run the code

Avoid building query strings by hand when values may contain spaces, symbols, or non-English characters.

Use URL and URLSearchParams so the browser handles encoding details for you.

Common beginner mistakes

  • Building query strings by hand and forgetting URL encoding.
  • Forgetting that values read from URLSearchParams are strings.
  • Assuming a parameter always exists without checking for null.

Run in browser

Try the example

Console output
Run the code to see console output here.
Exercise checks0 of 2 checks passed.
WaitingReads the existing query parameter
WaitingUpdates and encodes the URL

Code runs locally in a temporary browser worker with a timeout. It is not sent to Lumio analytics or executed on the server.

Try changing this next

  • Change `q=json` to `q=base64`.
  • Add another parameter with `set`.
  • Use `delete("page")` and print the URL again.