Is there a way to clear window.localStorage i.e window.localStorage.clear(); but exempt certain key/value pairs?
No, but you can save the values of what you want in a variable and then clear the localStorage and then add the items stored in the variable to it again.
Example:
var myItem = localStorage.getItem('key');
localStorage.clear();
localStorage.setItem('key',myItem);
Yes.
for( var k in window.localStorage) {
if( k == "key1" || k == "key2") continue;
// use your preferred method there - maybe an array of keys to exclude?
delete window.localStorage[k];
}
You could do this manually;
function clearLocalStorage(exclude) {
for (var i = 0; i < localStorage.length; i++){
var key = localStorage.key(i);
if (exclude.indexOf(key) === -1) {
localStorage.removeItem(key);
}
}
}
Note that I've purposefully taken the long winded approach of iterating over the length of localStorage and retrieving the matching key, rather than simply using for/in, as for/in of localStorage key's isn't specified in the spec. Older versions of FireFox barf when you for/in. I'm not sure on later versions (more info).
exclude is expected to be an array of keys you wish to exclude from being deleted;
clearLocalStorage(["foo", "bar"]);
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