How to remove only one of multiple key value pairs with the same key using URLSearchParams?

1k views Asked by At

I have an url in this form: https://www.example.com?tag[]=mountain&tag[]=hill&tag[]=pimple

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

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

2

There are 2 answers

1
idmean On BEST ANSWER

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);
1
Marten On

You could also just add it to the prototype of URLSearchParams so you can always easily use it 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 just remove a specific key, value pair from the URLSearchParams like this:

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