Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear localstorage values with certain prefix

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.

like image 876
Trishul Avatar asked Jul 03 '14 10:07

Trishul


People also ask

How do I delete a specific object in localStorage?

removeItem() : Remove an item by key from localStorage. clear() : Clear all localStorage. key() : Passed a number to retrieve the key of a localStorage.

How do I reset local storage value?

localStorage. clear(); Use this for clear all stored key. If you want to clear/remove only specific key/value then you can use removeItem(key).

What does localStorage Clear () do?

The clear() method removes all the Storage Object item for this domain. The clear() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.


1 Answers

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]); } 
like image 57
RonyHe Avatar answered Sep 22 '22 05:09

RonyHe