开发者

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

开发者 https://www.devze.com 2023-04-08 23:12 出处:网络
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

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

精彩评论

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

关注公众号