How to use URLSearchParams to delete one of multiple key-value pairs with the same key?
P粉214089349
P粉214089349 2023-12-30 23:40:07
0
2
506

I have a URL of the form: https://www.example.com?tag[]=mountain&tag[]=hill&tag[]=pimple

Now I want to delete one of them, let's say tag[]=hill. I know, I could use regex, but I'm using URLSearchParams to add these, so I want to use that to remove them as well. Unfortunately the delete() function deletes all pairs with the same key.

Is there a way to delete only a specific key-value pair?

P粉214089349
P粉214089349

reply all(2)
P粉904450959

You can also add it to the prototype of URLSearchParams so you can always use it easily in your code.

URLSearchParams.prototype.remove = function(key, value) {
    const entries = this.getAll(key);
    const newEntries = entries.filter(entry => entry !== value);
    this.delete(key);
    newEntries.forEach(newEntry => this.append(key, newEntry));
}

Now you can remove specific key-value pairs from URLSearchParams like this:

searchParams.remove('tag[]', 'hill');
P粉725827686

Do something like this:

const tags = entries.getAll('tag[]').filter(tag => tag !== 'hill');
entries.delete('tag[]');
for (const tag of tags) entries.append('tag[]', tag);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template