Reputation: 19
I am studying JavaScript and have been stuck on this for weeks! I need to remove these for items from local Storage. But using localStorage.removeItem('diary');
Will not work.
// Make a demo text item
data =
"Friday: We arrived to this wonderful guesthouse after a pleasant journey " +
"and were made most welcome by the proprietor, Mike. Looking forward to " +
"exploring the area tomorrow.";
item = makeDiaryItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000001";
// Store the item in local storage
localStorage.setItem(key, item);
// Make a demo text item
data =
"Saturday: After a super breakfast, we took advantage of one of the many " +
"signed walks nearby. For some of the journey this followed the path of a " +
"stream to a charming village.";
item = makeDiaryItem("text", data);
// Make a key using a fixed timestamp
key = "diary" + "1536771000002";
// Store the item in local storage
localStorage.setItem(key, item);`
Can someone point me in the right direction? Not looking for a direct answer.
Upvotes: 0
Views: 769
Reputation: 33901
If you want to remove all local storage items that begin with a prefix (e.g. "diary"
), you could use a function like this:
function removeLocalStorageItems (matcher) {
const keys = [];
for (let i = 0; i < localStorage.length; i += 1) {
const key = localStorage.key(i);
if (key) keys.push(key);
}
const shouldRemove = typeof matcher === 'function' ? matcher : (str) => matcher.test(str);
for (const key of keys) {
if (shouldRemove(key)) localStorage.removeItem(key);
}
}
function removeLocalStorageItemsByPrefix (prefix) {
removeLocalStorageItems(key => key.startsWith(prefix));
}
// Use:
removeLocalStorageItemsByPrefix('diary');
// or
removeLocalStorageItems(/^diary/);
Upvotes: 0
Reputation: 15540
You should remove item with the correct key. In your case, the key would be the combination between diary
and timestamp
It's possibly like this (because I'm seeing you're using that combination with key
variable)
localStorage.removeItem(key);
If it does not work, you can inspect your browser to see the proper key of your local storage (right click on your page and select Inspect
and after that you can look for Application
tab)
Upvotes: 0
Reputation: 20374
You need to specify correct keyname
that you want to remove from the Local Storage.
In your code, you are setting the item in the Local Storage with the keyname "diary1536771000002". BUT, you are trying to remove the item with keyname "diary".
Try this instead:
localStorage.removeItem('diary1536771000002');
Upvotes: 1