5

Is there a way to clear window.localStorage i.e window.localStorage.clear(); but exempt certain key/value pairs?

Szymon Toda
  • 4,454
  • 11
  • 43
  • 62
OliverJ90
  • 1,291
  • 2
  • 21
  • 42

3 Answers3

11

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
  • 58,320
  • 7
  • 77
  • 95
  • 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
7

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
  • 320,036
  • 81
  • 464
  • 592
  • 1
    I 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"]);
Community
  • 1
  • 1
Matt
  • 74,352
  • 26
  • 153
  • 180