Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to get query parameters from the page address

Short answer

location.search holds the part of the address after ?. URLSearchParams reads it:

// the address is https://example.com/catalog?category=tea&page=2
const params = new URLSearchParams(window.location.search);
 
const category = params.get('category'); // 'tea'
const page = Number(params.get('page') ?? 1); // 2

How it works

The same object works with any string, so you can try it without a browser:

const params = new URLSearchParams('?category=tea&page=2');
 
console.log(params.get('category'), params.get('page'));
console.log(params.has('sort'));

Output:

tea 2
false

Changing parameters

Change the parameters through URL and update the address with history.replaceState(). The page does not reload:

const url = new URL(window.location.href);
url.searchParams.set('page', '3');
history.replaceState(null, '', url);

Common mistake

get() returns null for a missing parameter, and numbers come as strings. Add a default value and convert the type:

const params = new URLSearchParams('?q=tea');
 
console.log(params.get('page'));
console.log(Number(params.get('page') ?? 1));

Output:

null
1

Functions used in this recipe

  • URLSearchParams — Reads and builds URL query parameters (the part after ?).
  • URL — Parses an address into parts and builds it back.

Thanks for reading!

Donate to the site — we work hard for you.