Query strings often carry filters, page numbers, campaign labels, return targets, and feature flags into browser pages. JavaScript reads those values through the URL and URLSearchParams APIs, which keep parameter lookup tied to the browser's URL parser instead of fragile string splitting.
The searchParams object exposes decoded query arguments by name. get() returns the first value for a key or null when the key is absent, getAll() preserves repeated keys as an array, and has() checks whether a flag-like key exists at all.
Every value from URLSearchParams is a string until the code converts it. Handle missing keys, repeated keys, empty values, and numeric parsing before query data changes page state, especially when a URL can be copied, bookmarked, or edited by hand. Treat query parameters as user-controlled input; server-side authorization, pricing, ownership, and other sensitive decisions still need server-side validation.
Related: How to debug JavaScript in the browser console
Tool: URL Parser
function readProductFilters(locationHref = window.location.href) { const url = new URL(locationHref); const params = url.searchParams; return { category: params.get("category") ?? "all", page: Number(params.get("page") ?? "1"), tags: params.getAll("tag"), preview: params.has("preview"), }; } const filtersWithQuery = readProductFilters( "https://www.example.com/products?category=books&page=2&tag=javascript&tag=web&preview", ); const filtersWithoutQuery = readProductFilters("https://www.example.com/products"); console.log("with query:"); console.log(JSON.stringify(filtersWithQuery, null, 2)); console.log("without query:"); console.log(JSON.stringify(filtersWithoutQuery, null, 2));
Pass a sample URL during tests. In browser page code, calling readProductFilters() without an argument reads window.location.href.
params.get(“category”) ?? “all” keeps a missing category from becoming null in the returned state. Number(params.get(“page”) ?? “1”) converts the query string into a number after the fallback is chosen; validate the range before using it for pagination.
The sample URL contains two tag keys, so params.getAll(“tag”) returns both values in URL order. Use get(“tag”) only when the first value is the intended behavior.
params.has(“preview”) returns true for a present key such as preview even when no value follows it. Use get() when the value itself matters.
$ node read-url-parameters.mjs
with query:
{
"category": "books",
"page": 2,
"tags": [
"javascript",
"web"
],
"preview": true
}
without query:
{
"category": "all",
"page": 1,
"tags": [],
"preview": false
}
The without query block confirms the missing-parameter defaults, and the with query block confirms repeated tag values and the preview flag.