Javascript HTML5 Localstorage & jQuery:删除以某个单词开头的 localstorage 键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7591893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:50:31  来源:igfitidea点击:

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

javascriptjqueryhtmllocal-storage

提问by jQuerybeast

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.

我有 2 个应用程序与 localstorage 一起工作,我想知道如何删除所有以 note- 和 todo- 开头的键。我知道 localstorage.clear() 清除所有内容,但这不是我的目标。

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.

我想通过单击按钮删除所有 todo-* 以及使用 jquery 单击其他按钮删除所有 note-*。

Thanks alot

非常感谢

回答by Ghostoy

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

回答by WEFX

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.

我使用了与 @Ghostoy 类似的方法,但我想输入一个参数,因为我从代码中的多个位置调用它。我无法在正则表达式中使用我的参数名称,所以我只使用了子字符串。

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

    Object.keys(localStorage) 
        .forEach(function(key){ 
            if (key.substring(0,myLength) == startsWith) {
                localStorage.removeItem(key); 
            } 
        }); 
}