21

I have 2 apps working together with localstorage and I was wondering how can I delete all the keys which start with note- and todo- . I know localstorage.clear() clears everything but thats not my aim.

Here is an example of what I have in my localstorage: enter image description here

Where I want to delete all the todo-* with a button click and all note-* with other button click using jquery.

Thanks alot

jQuerybeast
  • 14,130
  • 38
  • 118
  • 196

2 Answers2

43
Object.keys(localStorage)
      .forEach(function(key){
           if (/^todo-|^note-/.test(key)) {
               localStorage.removeItem(key);
           }
       });
Ghostoy
  • 2,689
  • 19
  • 18
  • it seems to delete the todo-'s only ? Weird – jQuerybeast Sep 29 '11 at 03:01
  • 3
    The RegEx should be `/^(?:todo-|note-)/`. The `?:` will make it a non-capturing group which will speed things up a little. `/^todo-|^note-/` should work too without any grouping at all. – Useless Code Sep 29 '11 at 03:08
  • It doesn't seem to be that the problem. I think the problem is in the coding of that app because I tried to delete the value through firebug and when I refresh I get it the value back. – jQuerybeast Sep 29 '11 at 03:13
10

I used a similar method to @Ghostoy , but I wanted to feed in a parameter, since I call this from several places in my code. I wasn't able to use my parameter name in a regular expression, so I just used substring instead.

function ClearSomeLocalStorage(startsWith) {
    var myLength = startsWith.length;

    Object.keys(localStorage) 
        .forEach(function(key){ 
            if (key.substring(0,myLength) == startsWith) {
                localStorage.removeItem(key); 
            } 
        }); 
}
WEFX
  • 8,298
  • 8
  • 66
  • 102