开发者

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 but thats not my aim.

Here is an example of what I have in my localstorage:

HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

Where I want to delete all the todo-开发者_JS百科* with a button click and all note-* with other button click using jquery.

Thanks alot


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜