In my application I would like that in a moment all the keys of my localstorage will be deleted, with the exception of all the keys that contain the word "wizard".
Commands such as
localstorage.clear();
will erase everything, and I just want to keep those that have the word "wizard", I have tried in this way, but I get errors because if I delete a match, in the next iteration a key will be skipped, I will get the error that is trying to search a match in a position that will now be null, since it has been deleted. how can I solve that?
this is my code:
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
//if the key not contain the word "wizard" will be erased
if( localStorage.getItem(localStorage.key(i)).search("wizard")==-1){
localstorage.removeItem( localStorage.getItem( localStorage.key( i ) ) );
}
}
To delete local storage sessions, use the removeItem() method. When passed a key name, the removeItem() method removes that key from the storage if it exists. If there is no item associated with the given key, this method will do nothing.
The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
The clear() method of the Storage interface clears all keys stored in a given Storage object.
key() The key() method of the Storage interface, when passed a number n, returns the name of the nth key in a given Storage object.
You can iterate over the entries
of localStorage
, and delete the key if the value includes wizard
:
localStorage.foo = 'foo';
localStorage.bar = 'wizard1';
localStorage.baz = 'wizard2';
localStorage.buzz = 'buzz';
Object.entries(localStorage).forEach(([key, val]) => {
if (!val.includes('wizard')) delete localStorage[key];
});
console.log(Object.keys(localStorage));
Result: only bar
and baz
keys will remain.
(Cannot post as embedded snippet because stack snippets do not support localStorage)
https://jsfiddle.net/cLm3kg01/
If you want to keep key names which contain wizard
rather than values that contain wizard
, then use Object.keys
instead of Object.entries
to iterate over the keys:
localStorage.wizard1 = 'foo';
localStorage.wizard2 = 'bar';
localStorage.baz = 'baz';
localStorage.buzz = 'buzz';
Object.keys(localStorage).forEach((key) => {
if (!key.includes('wizard')) delete localStorage[key];
});
console.log(Object.keys(localStorage));
https://jsfiddle.net/cLm3kg01/6/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With