Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda