使用特定前缀清除localstorage值

Tri*_*hul 19 javascript html5 local-storage

我已经存储了几个键值对,其中包含使用HTML5 localstorage变量的某些加密登录信息.我为所有关键名称添加了一个唯一的前缀TM_loginname.现在我想清除所有localstorage键值对,其键以前缀TM_开头.PS:我也尝试过sessionstorage,但只有在浏览器关闭时它才会清除.

Ron*_*yHe 37

迭代时删除元素是不安全的,因此创建一个数组来保存需要删除的键.然后,遍历该数组以删除它们:

var arr = []; // Array to hold the keys
// Iterate over localStorage and insert the keys that meet the condition into arr
for (var i = 0; i < localStorage.length; i++){
    if (localStorage.key(i).substring(0,3) == 'TM_') {
        arr.push(localStorage.key(i));
    }
}

// Iterate over arr and remove the items by key
for (var i = 0; i < arr.length; i++) {
    localStorage.removeItem(arr[i]);
}
Run Code Online (Sandbox Code Playgroud)

  • **更多:** `(localStorage.key(i).indexOf(path_key) &gt;= 0)` 也可以使用,或者使用变量使其更具可扩展性:`...substring(0, prefix.length) = =前缀` (2认同)

tbe*_*nst 9

更现代的(ES2017)解决方案如下:

Object.entries(localStorage).map(
        x => x[0] # get keys
    ).filter(
        x => x.substring(0,3)=="TM_"
    ).map(
        x => localStorage.removeItem(x))
Run Code Online (Sandbox Code Playgroud)

  • `x.startsWith` 会比 `x.substring` 更干净吗? (2认同)
  • 由于您需要密钥,因此可以使用 Object.keys(localStorage) 代替 `Object.keys(localStorage).filter(x =&gt; x.startsWith('TM_')).forEach(x =&gt; localStorage.removeItem(x) )` (2认同)

Die*_*iar 6

使用lodash.请享用.

_.forIn(window.localStorage, (value: string, objKey: string) => {
    if (true === _.startsWith(objKey, 'TM_')) {
        window.localStorage.removeItem(objKey);
    }
});
Run Code Online (Sandbox Code Playgroud)