2

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 Answers2

3

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);
idmean
  • 14,540
  • 9
  • 54
  • 83
  • 1
    Yes, that'll work fine, thank you! Still strange that there really is no built-in way to do this as with get and getAll. Feels like an oversight, it can't be that uncommon of an usecase. – DM_Resources Dec 10 '20 at 20:37
1

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');
Marten
  • 645
  • 7
  • 21
  • 1
    That's a really neat idea, I'll do that if I need that more than once in my code. Thank you! – Merion Feb 13 '22 at 23:38