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