Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 768
Jesse Atkinson Avatar asked Nov 07 '13 19:11

Jesse Atkinson


2 Answers

You could do something like

Object.keys(sessionStorage)
  .filter(function(k) { return /foo/.test(k); })
  .forEach(function(k) {
    sessionStorage.removeItem(k);
  });
like image 31
Pointy Avatar answered Sep 28 '22 06:09

Pointy


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/

like image 114
roland Avatar answered Sep 28 '22 06:09

roland