skip to Main Content

I’ve got this code working fine. But The delete() function deletes all entries with the key equal to "foo".

`let url = new URL("https://example.com?foo=1&bar=2");
let params = new URLSearchParams(url.search);

 //Add a second foo parameter.
 url.searchParams.append("foo", 4);

 console.log(params.getAll("foo")); //Prints ["1","4"].
 console.log(url)
 url.searchParams.delete("foo", 4);
 console.log(url)`

The goal is to delete only one of entry (foo=4) and

2

Answers


  1. How about using indexof?

    // Find the index of the entry to delete.
    let index = params.getAll("foo").indexOf("4");
    
    // If the value was found, remove it.
    if (index !== -1) {
      params.getAll("foo").splice(index, 1);
    }
    
    Login or Signup to reply.
  2. The value option in delete method is not being supported by major browsers other than Firefox, and Node.js only supports the syntax starting from version 20. One way to resolve it is to get all values associated with the search parameter url.searchParams.getAll("foo"), filter out the one with undesired value, delete all search parameters with the name foo, and finally add the desired ones back.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search