A search page uses a repeated tag parameter for a multi-select filter and a single page parameter for pagination. When the user changes tags, replace the old tag values and reset the page without discarding sort order. Treat the query as a sequence of name-value pairs, not an object that can hold only one value for each key.
Use append for values that may repeat
Use a supported Node.js release to run the checks below. The helper uses standard URL APIs and can also be used in browser code. Save the example as filters.mjs. It copies the query into a detached URLSearchParams instance so the original URL remains available unchanged.
import assert from 'node:assert/strict';
function updateFilters(url, tags) {
const params = new URLSearchParams(url.search);
params.delete('tag');
for (const tag of tags) params.append('tag', tag);
params.set('page', '1');
return params;
}
const original = new URL('https://example.test/?tag=old&sort=new&page=8&page=9');
const result = updateFilters(original, ['C++', 'machine learning']);
assert.deepEqual(result.getAll('tag'), ['C++', 'machine learning']);
assert.deepEqual(result.getAll('page'), ['1']);
assert.equal(result.get('sort'), 'new');
assert.deepEqual(new URLSearchParams(result.toString()).getAll('tag'), result.getAll('tag'));
assert.deepEqual(updateFilters(original, []).getAll('tag'), []);
assert.deepEqual(original.searchParams.getAll('page'), ['8', '9']);
console.log(result.toString());Run node filters.mjs. Expected output:
sort=new&page=1&tag=C%2B%2B&tag=machine+learningUse the operation that matches each parameter
delete removes all old tag values. Appending the new values preserves their order, including duplicates if the caller supplies them. By contrast, set keeps only one value for pagination. It updates the first occurrence and removes later ones. Read a multi-valued filter with getAll. Clearing the filter supplies no tag keys at all, rather than a single tag whose value is empty. Decide explicitly which of those states your server accepts.
Troubleshoot plus signs and unwanted navigation
Supply literal values such as C++ to append. Pre-encoding them would encode the percent signs again. If the application already received a raw query containing C++ without percent escapes, parsing treats those plus signs as spaces. Copying the query preserves decoded name-value pairs, not necessarily the exact spelling of the original percent escapes. Do not use this helper to rewrite a query whose original bytes must be preserved, such as a signed link. The helper returns only parameters and does not navigate. To apply it, assign the serialized result to the search property of a separate URL and let the caller choose when to navigate.
Primary reference and related tutorials: WHATWG URLSearchParams specification · Java Samples JavaScript tutorials.