Home > Back-end >  Remove a URL search parameter when there is duplicate names?
Remove a URL search parameter when there is duplicate names?

Time:12-04

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.

CodePudding user response:

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

CodePudding user response:

Try this approach:

const deleteURLParamsByNameAndValue = (urlString, paramName, paramValue) => {
  const url = new URL(urlString)
  const params = url.searchParams
  const newParamArray = []
  for (var kvPair of params.entries()) {
    const k = kvPair[0]
    const v = kvPair[1]
    if (k!==paramName || v!==paramValue) {
      newParamArray.push(kvPair)
    }
  }
  const newSearch = new URLSearchParams(newParamArray)
  return decodeURI(`${url.origin}${url.pathname}?${newSearch}`)
}

const urlString = 'https://example.com/path1/path2?color[]=Black&color[]=Green&material[]=Steel'

deleteURLParamsByNameAndValue(urlString,'color[]','Black')
// returns 'https://example.com/path1/path2?color[]=Green&material[]=Steel'
  • Related