javascriptphpurl

Remove a URL search parameter when there is duplicate names?


I am trying to manipulate my URL using URLSearchParams. However URLSearchParams.delete() expects the name of the param. If I have params with the same name, (from what I've tested in chrome) It will delete all params with that name. Is there a way to delete by both name and value?

My query looks something like this:

?color[]=Black&color[]=Green&material[]=Steel

So when I call .delete("color[]") it will remove both color[]= params, but what if I want to only remove a specific one?

The reason for the duplicate names is the backend (PHP) is leveraging this functionallity to auto parse the parameters into arrays...which requires the syntax above.

Big picture is- I'm trying to add/remove "filters" from this array-to-be. Also, some filter categories could have matching values so I don't want remove by value either. I am open to considering an entirely new approach...just trying to do it in the least hacky way.

-- Edit --

For any Laravel users, I recommend not using the index-less syntax. Just use color[0]=, color[1]= etc. I didn't realize laravel supports both syntaxes.


Solution

  • To remove a specific key/value pair, loop over the entries, filter out the unwanted one(s) and create a new URLSearchParams:

    function deleteParamsEntry(params, key, value) {
        const newEntries = Array.from(params.entries()).filter(
          ([k, v]) => !(k === key && v === value)
        );
       return new URLSearchParams(newEntries);
    }
    
    const query = "?color[]=Black&color[]=Green&material[]=Steel";
    const params = new URLSearchParams(query);
    
    const newParams = deleteParamsEntry(params, "color[]", "Green");
    
    console.log(newParams.toString());