Web 存储 API 会话存储:删除 XYZ 等所有键

Web Storage API Session Storage: delete all keys like XYZ

给定以下 HTML 会话数据:

hasSession                            1
user                                  user_abc
CosttoServe599a8e8421a80              25
runningTotal                          100
Maintenance599a8e8421a80              5
BusinessEnhancements599a8e8421a80     25
BusinessEnhancements599a8e8421a94     25
Maintenance599a8e8421a94              10
FrontierInvestments599a8e8421a94      5
CosttoServe599a8e8421a86              0
FrontierInvestments599a8e8421a86      5

我正在尝试删除包含以下内容的所有密钥:

599a8e8421a94

有什么方法可以在会话存储上执行 like/wild 卡类型删除吗?

遍历 sessionStorage 对象并检查键是否包含 599a8e8421a94,如果包含,则将其删除:

for (var key in sessionStorage) {
    if (key.indexOf('599a8e8421a94') !== -1)
        sessionStorage.removeItem(key);
}

一个实际的例子:

/**  Define dummy data... **/
var obj = {
    'no-clean': 'i will not be cleaned.',
    'testing599a8e8421a94': 25,
    'another_test599a8e8421a94': 'e,ndleknfew',
    '599a8e8421a94somemoretesting': '2knmsdkgsdg'
};

/** Loop through our dummy data and add it to sessionStorage. **/
for (var key in obj) {
    sessionStorage.setItem(key, obj[key]);
}

/** This is the part you will need, loop through sessionStorage object. **/
for (var key in sessionStorage) {
    /** Check if the key contains the search string... **/
    if (key.indexOf('599a8e8421a94') !== -1)
        sessionStorage.removeItem(key)
}

console.log(sessionStorage)

JSFiddle - 打开控制台可以看到sessionStorage对象中剩余的key/value。

阅读Material

How to check whether a string contains a substring in JavaScript?