Re: [whatwg/url] URLSearchParams delete all vs delete one (#335)

When using @ShaneHudson's solution, be aware that `allValues.indexOf("Alice")` will return `-1` if no key/value pair exists for that value. If `query` did not contain any entries with the value `"Alice"`, then `allValues.splice(-1, 1)` would delete the last item in `allValues`, which is probably not what you want.

Here's a version which avoids this pitfall:

```
function deleteSearchParamByKeyValue (searchParams, key, value) {
  const allKeys = []
  const entriesToKeep = []

  for (const [k, v] of searchParams.entries()) {
    if (k === undefined || v === undefined) continue
    allKeys.push(k)
    if (k === key && v === value) continue
    entriesToKeep.push([k, v])
  }

  for (const k of allKeys) {
    searchParams.delete(k)
  }

  for (const [k, v] of entriesToKeep) {
    searchParams.append(k, v)
  }
}
```

Another difference is that this version will delete all entries which match the given `key` and `value`, whereas @ShaneHudson's version will delete only the first match.


-- 
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/url/issues/335#issuecomment-1221604291
You are receiving this because you are subscribed to this thread.

Message ID: <whatwg/url/issues/335/1221604291@github.com>

Received on Sunday, 21 August 2022 19:12:49 UTC