Clear local storage, but free certain values.

Is there any way to clear window.localStorage ie window.localStorage.clear(); but release certain key / value pairs?

+1
javascript
source share
3 answers

No, but you can save the values โ€‹โ€‹of what you want in a variable and then clear localStorage and then add the elements stored in the variable again.

Example:

 var myItem = localStorage.getItem('key'); localStorage.clear(); localStorage.setItem('key',myItem); 
+5
source share

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]; } 
+2
source share

You can do it 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); } } } 

Please note that I deliberately used a lengthy iteration method over the length of localStorage and retrieved the match key, not just using for/in , because the for/in of the localStorage key localStorage not specified in the specification. Older versions of FireFox barf when you are for/in . I am not sure about the later versions ( more ).

exclude is expected an array of keys that you want to exclude from deletion;

 clearLocalStorage(["foo", "bar"]); 
+1
source share

All Articles