Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear local storage but exempt certain values.

Tags:

javascript

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

like image 697
OliverJ90 Avatar asked Apr 16 '14 15:04

OliverJ90


3 Answers

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);
like image 99
Amit Joki Avatar answered Oct 14 '22 05:10

Amit Joki


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];
}
like image 37
Niet the Dark Absol Avatar answered Oct 14 '22 07:10

Niet the Dark Absol


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"]);
like image 21
3 revs Avatar answered Oct 14 '22 07:10

3 revs