M
M
Marat Ivanov2021-01-28 07:05:38
JavaScript
Marat Ivanov, 2021-01-28 07:05:38

How to filter keys in URLSearchParams?

Guys, tell me pliz, there is an array of keys by which you need to filter the keys in URLSearchParams. that is, leave in URLSearchParams only those keys that are specified in the array of valid keys.
for example how to delete the key utm_delete=delete

export enum UtmType {
    UtmSource = 'utm_source',
    UtmMedium = 'utm_medium',
  }
const url = '?utm_source=stop&utm_medium=get&utm_delete=delete'
const params = new URLSearchParams(url)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-01-28
@mrair

for (const key of utm) {
    params.delete(key);
}

UPD :
const href = 'https://example.com/?user=John&some_key=1&id=3';
const url = new URL(href);
const availableKeys = ['user', 'id'];
for (const key of [...url.searchParams.keys()]) {
    if (!availableKeys.includes(key)) {
        url.searchParams.delete(key);
    }
}
console.log(url.toString()); // 'https://example.com/?user=John&id=3'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question