Is there a way to clear window.localStorage i.e window.localStorage.clear(); but exempt certain key/value pairs?
Asked
Active
Viewed 1,350 times
5
Szymon Toda
- 4,195
- 11
- 40
- 61
OliverJ90
- 1,251
- 1
- 20
- 41
3 Answers
9
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);
Amit Joki
- 56,285
- 7
- 72
- 91
-
This was pretty much what I was planning on doing but wanted to see if there was a generally accepted way, seems like this is it! – OliverJ90 Apr 16 '14 at 15:30
5
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];
}
Niet the Dark Absol
- 311,322
- 76
- 447
- 566
-
1I looked at this way first; turns out the localStorage spec doesn't include the enumeration of for/in. Older versions of FireFox (at the very least) barf (http://stackoverflow.com/a/5410884/444991). – Matt Apr 16 '14 at 15:27
2
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"]);