Is there a way to remove all sessionStorage items with keys that match a certain pattern?
Asked Answered
C

5

20

Lets say my sessionStorage contains three objects who's keys are foo, foobar, and baz. Is there a way that I can call .removeItem or somehow delete all items in sessionStorage who's keys match foo? In this example I'd be left with only the item who's key is baz.

Coated answered 7/11, 2013 at 19:20 Comment(0)
T
41

Update September 20, 2014 As pointed out by Jordan Trudgett the reverse loop is more appropriate

You can only achieve it programmatically as sessionStorage exposes a limited set of methods: getItem(key), setItem(key, value), removeItem(key), key(position), clear() and length():

var n = sessionStorage.length;
while(n--) {
  var key = sessionStorage.key(n);
  if(/foo/.test(key)) {
    sessionStorage.removeItem(key);
  }  
}

See Nicholas C. Zakas' blog entry for more details:

http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/

Tang answered 7/11, 2013 at 19:28 Comment(3)
You should iterate over the storage object in reverse order, because when you remove the item, the indexes get changed. Doing it this way may miss some items.Barrybarrymore
It should be mentioned that unlike other arrays, sessionStorage keys are indexed from 1 to sessionStorage.length. If you were to use a for loop, the indices should be correct.Know
If you have pattern in variable as a string - var patternStr = 'foo'; you can use (new RegExp(patternStr)).test(key)Philips
G
14

You could do something like

Object.keys(sessionStorage)
  .filter(function(k) { return /foo/.test(k); })
  .forEach(function(k) {
    sessionStorage.removeItem(k);
  });
Girdle answered 7/11, 2013 at 19:25 Comment(0)
I
2

Since both local and sessionStorage are objects you can go through their properties like this:

    for (var obj in localStorage) {
      if (localStorage.hasOwnProperty(obj) && obj == "myKey") {
        localStorage.removeItem(obj);
      }
    }

and remove the desired values by key, here it's "myKey" for example.

Infuscate answered 22/1, 2015 at 12:8 Comment(0)
E
2

Remove all session storage items:

sessionStorage.clear()
Extrabold answered 20/1, 2022 at 17:13 Comment(0)
K
-1

Try this:

 angular.forEach(sessionStorage, function (item,key) {
          sessionStorage.removeItem(key);
      });

This will delete everything from sessionStorage

Kinetics answered 24/11, 2016 at 7:30 Comment(1)
There is no Angular tag, so your answer isn't useful in this context.Kimmy

© 2022 - 2024 — McMap. All rights reserved.