Reputation: 1028
I have stored several key value pairs which contains certain encrypted login information using HTML5 localstorage variables. I have added a unique prefix to all key names say TM_loginname
. Now I want to clear all the localstorage key-value pairs whose key starts with prefix TM_.
PS: I tried sessionstorage too, but it clears only when browser is closed.
Upvotes: 43
Views: 27791
Reputation: 1050
A more modern (ES2017) solution is as follows:
Object.entries(localStorage).map(
x => x[0] # get keys
).filter(
x => x.substring(0,3)=="TM_"
).map(
x => localStorage.removeItem(x))
EDIT
Taken from the comments:
Object.keys(localStorage)
.filter(x =>
x.startsWith('TM_'))
.forEach(x =>
localStorage.removeItem(x))
Upvotes: 22
Reputation: 2565
Adapting the tip of 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; }
And after, calling the function:
var keysFounded = findLocalItems(key);
if (keysFounded && keysFounded.length > 0) {
keysFounded.forEach(k => {
localStorage.removeItem(k.key);
});
}
Upvotes: 1
Reputation: 71288
save to localStorage using
key = pref + version
function remLSPref(pref, newName) {
for (var key in localStorage) {
if (key.indexOf(pref) == 0) {
if (key != newName) {
localStorage.removeItem(key);
}
}
}
}
and use like this:
var pref = 'myid_';
var key = pref + ver;
// rem old ls
remLSPref(pref, key);
Upvotes: 4
Reputation: 3302
Using lodash. Enjoy.
_.forIn(window.localStorage, (value: string, objKey: string) => {
if (true === _.startsWith(objKey, 'TM_')) {
window.localStorage.removeItem(objKey);
}
});
Upvotes: 11
Reputation: 942
Removing element while iterating is unsafe, so create an array to hold the keys that need to be removed. Then, iterate over that array to remove them:
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]);
}
Upvotes: 61
Reputation: 25321
You can either:
Upvotes: 1