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

前端 未结 2 818
春和景丽
春和景丽 2020-12-25 13:23

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 ever

相关标签:
2条回答
  • 2020-12-25 14:00

    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 讨论(0)
  • 2020-12-25 14:02
    Object.keys(localStorage)
          .forEach(function(key){
               if (/^todo-|^note-/.test(key)) {
                   localStorage.removeItem(key);
               }
           });
    
    0 讨论(0)
提交回复
热议问题