Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

162
Visualizações
Deleting URL parameters using URLSearchParams

I'm utilizing the URLSearchParams API to delete keys/values from the query string in my URL.

I have the following snippet:

params = new URLSearchParams('a=x&b=y&c=z');
params.forEach(function(value, key){
  console.log("Deleted: ", key, value, params.toString());
  params.delete(key);
});
console.log("Left with: ", params.toString());

Invariably, the Left with: returns part of the query parameters.

Output on this JSFiddle:

☁️ "Running fiddle"
"Deleted: ", "a", "x", "a=x&b=y&c=z"
"Deleted: ", "c", "z", "b=y&c=z"
"Left with", "b=y"

My understanding of forEach() is that it'll loop over all the key/value pairs, but based on this fiddle, it looks like it exits the loop on the penultimate pair.

Edit, based on feedback in the comments below:

I'm trying to selectively retain one or two parameters (based on a list provided).

params = new URLSearchParams('a=x&b=y&c=z&d=1');
params.forEach(function(value, key){
  retainList = ['d'];
  if (retainList.includes(key)){
    console.log("Retaining ", key);
  } else {
    console.log("Deleted: ", key, value, params.toString());
    params.delete(key);
  }
});
console.log("Left with: ", params.toString());
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Seems to be some odd reference issue happening with URLSearchParams. Even when you use the .keys() method to get a list of keys it seems like it's giving a reference to it's internal list of keys.

You can work around this issue by cloning the list of keys using spread

params = new URLSearchParams('a=x&b=y&c=z');
keys = [...params.keys()]
for (key of keys) {
  console.log("Deleting: ", key, params.get(key), params.toString());
  params.delete(key)
};
console.log("Left with: ", params.toString());

To achieve the desired result you could do:

params = new URLSearchParams('a=x&b=y&c=z&d=1');
retainList = ['d']

for (key of [...params.keys()]) {
  if (! retainList.includes(key)) {
    console.log("Deleting: ", key, params.get(key), params.toString());
    params.delete(key)
  }
};
console.log("Left with: ", params.toString());

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda