Search code examples
javascriptwebapiurlsearchparams

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


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?


Solution

  • 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);