DM_Resources
DM_Resources

Reputation: 37

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?

Upvotes: 2

Views: 1211

Answers (2)

Marten
Marten

Reputation: 854

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

Upvotes: 1

idmean
idmean

Reputation: 14905

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

Upvotes: 3

Related Questions