Google examples

Example1

// Can also constructor from another URLSearchParams
const params = new URLSearchParams('q=search+string&version=1&person=Eric');

params.get('q') === "search string"
params.get('version') === "1"
Array.from(params).length === 3

append another value for an existing parameter:

params.append('person', 'Tim');
params.getAll('person') === ['Eric', 'Tim']

delete a parameter(s):

params.delete('person');

Working with URLs

Most of the time, you’ll probably be working with full URLs or modifying your app’s URL. The URL constructor can be particularly handy for these cases:

const url = new URL('https://example.com?foo=1&bar=2');
const params = new URLSearchParams(url.search);
params.set('baz', 3);

params.has('baz') === true
params.toString() === 'foo=1&bar=2&baz=3'

To make actual changes to the URL, you can grab parameters, update their values, then use history.replaceState to update the URL.

// URL: https://example.com?version=1.0
const params = new URLSearchParams(location.search);
params.set('version', 2.0);

window.history.replaceState({}, '', `${location.pathname}?${params}`);
// URL: https://example.com?version=2.0