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

416 views

12

function getQueryParam(name, source = typeof location !== 'undefined' ? location.search : '') {
    const params = new URLSearchParams(source);
    return params.get(name);
}

console.log(getQueryParam('q', '?q=hello&page=2'));  // hello
console.log(getQueryParam('missing', '?q=hello'));   // null
console.log(getQueryParam('q', '?q=hello&q=world')); // hello (first)

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).