Skip to content
Advertisement

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

Advertisement

Answer

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());
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement