Skip to content Skip to sidebar Skip to footer

Html5 Localstorage & Jquery: Delete Localstorage Keys Starting With A Certain Word

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

Solution 1:

Object.keys(localStorage)
      .forEach(function(key){
           if (/^todo-|^note-/.test(key)) {
               localStorage.removeItem(key);
           }
       });

Solution 2:

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); 
            } 
        }); 
}

Post a Comment for "Html5 Localstorage & Jquery: Delete Localstorage Keys Starting With A Certain Word"