JavaScript Snippet

Read a URL Query Parameter

Difficulty: Easy

Reading `?q=hello` is a one-liner with `URLSearchParams`, but the helpers around it (multi-value params, defaults, type coercion, updating without reload) are where most apps end up duplicating code. This snippet covers the basic read, a typed-default helper, and a setter that updates the URL with `history.replaceState` so the back button keeps working. Use it for filters, search inputs, and shareable links.

Code Snippets
/

Read a URL Query Parameter

Read a URL Query Parameter

Reading `?q=hello` is a one-liner with `URLSearchParams`, but the helpers around it (multi-value params, defaults, type coercion, updating without reload) are where most apps end up duplicating code. This snippet covers the basic read, a typed-default helper, and a setter that updates the URL with `history.replaceState` so the back button keeps working. Use it for filters, search inputs, and shareable links.

JavaScript
Easy
3 snippets
js-web-apis
js-dom
utility
code-template

415 views

12

URLSearchParams parses any query-style string and exposes a Map-like API. Calling .get(name) returns the first occurrence as a string or null when the key is missing. Defaulting source to location.search lets the helper run anywhere a URL string can be passed (server-side requests, parsed URL objects, hash routes), which makes it easy to test without a real location. Note that .get always returns the first occurrence; for repeated keys (?tag=a&tag=b), use .getAll(name).