Home  >  Q&A  >  body text

How to use URLSearchParams to delete one of multiple key-value pairs with the same key?

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粉214089349P粉214089349293 days ago462

reply all(2)I'll reply

  • P粉904450959

    P粉9044509592023-12-31 19:04:33

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

    reply
    0
  • P粉725827686

    P粉7258276862023-12-31 13:27:11

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

    reply
    0
  • Cancelreply