9

with localstorage i have a load of unspecified items saved with dynamic names using a data namespace like so:

localStorage["myAppName.settings.whatever"] = something.whatever; 

//and this:
localStorage["myAppName.data."+dynObj.name] = dynObj.data;

I want to keep the settings but not the data. However I won't ever know what all of the names inside of my data object are so I cannot clear them individually. I need to clear these each time my app is loaded but I must keep the settings so localstorage.clear() is not an option.

I have tried:

localstorage.removeItem("myAppName.data")

but no dice.

Anyone have any thoughts on how to clear dynamically named portions of localstorage?

Alex
  • 3,732
  • 5
  • 37
  • 59
  • It's a shame that localStorage doesn't include a namespace as part of the basic API. In the meantime, there's this: https://github.com/joelarson4/LSNS – jwl Dec 21 '12 at 21:51

4 Answers4

20

You can loop through the keys in the localStorage and target them with a reg exp:

Object.keys(localStorage)
      .forEach(function(key){
           if (/^(myAppName.data.)/.test(key)) {
               localStorage.removeItem(key);
           }
       });  

Here's a similar question: HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

Community
  • 1
  • 1
Niklas
  • 13,005
  • 23
  • 79
  • 119
2

try something like

var i = localStorage.length, key;
while (i--) {
  key = localStorage.key(i);
  if (key.slice(0, 19) !== "myAppName.settings.") {
    localStorage.remove(key);
  }
}
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
0

Assuming a this.namespace present (in my case 'session') and the underscore library:

_.each(_.keys(localStorage), function(key) {
  if (RegExp("^" + this.namespace + "\\.").test(key)) {
    return localStorage.removeItem(key);
  }
});

And with CoffeeScript:

_.each _.keys(localStorage), (key) ->
  if ///^#{@namespace}\.///.test(key)
    localStorage.removeItem(key)
Dorian
  • 22,759
  • 8
  • 120
  • 116
0

Tried something like this?

// Select current settings
var settings = localStorage["myAppName.settings"] || {};
// Clear localStorage
localStorage.clear();
// Add settings to localStorage
localStorage["myAppName.settings"] = settings;
Stefan
  • 5,644
  • 4
  • 24
  • 31