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