使用特定前缀清除localstorage值

时间:2014-07-03 10:44:56

标签: javascript html5 local-storage

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

6 个答案:

答案 0 :(得分:34)

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

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

答案 1 :(得分:5)

使用lodash。享受。

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

答案 2 :(得分:3)

使用保存到localStorage key = pref + version

function remLSPref(pref, newName) {
    for (var key in localStorage) {
        if (key.indexOf(pref) == 0) {
            if (key != newName) {
                localStorage.removeItem(key);
            }
        }
    }
}

并使用如下:

var pref = 'myid_';
var key = pref + ver;

// rem old ls
remLSPref(pref, key);

答案 3 :(得分:1)

你可以:

答案 4 :(得分:0)

适应github的提示:

findLocalItems(query) {
var i,
  results = [];
for (i in localStorage) {
  if (localStorage.hasOwnProperty(i)) {
    if (i.match(query) || (!query && typeof i === 'string')) {
      var value = JSON.parse(localStorage.getItem(i));
      results.push({ key: i, val: value });
    }
  }
}
return results;  }

然后,调用函数:

var keysFounded = findLocalItems(key);
if (keysFounded && keysFounded.length > 0) {
  keysFounded.forEach(k => {
    localStorage.removeItem(k.key);
  });
}

答案 5 :(得分:0)

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

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