Categories
JavaScript Answers

How to remove all session storage items with keys that match a certain pattern with JavaScript?

Spread the love

Sometimes, we want to remove all session storage items with keys that match a certain pattern with JavaScript.

In this article, we’ll look at how to remove all session storage items with keys that match a certain pattern with JavaScript.

How to remove all session storage items with keys that match a certain pattern with JavaScript?

To remove all session storage items with keys that match a certain pattern with JavaScript, we can loop through the keys of the items we want to remove and remove the entries with the keys.

For instance, we write:

const keys = Object.keys(sessionStorage)
  .filter((k) => {
    return /foo/.test(k);
  })

for (const k of keys) {
  sessionStorage.removeItem(k);
}

to get the keys of the items we want to remove with:

const keys = Object.keys(sessionStorage)
  .filter((k) => {
    return /foo/.test(k);
  })

Then we loop through the keys with a for-of loop.

In it, we call sessionStorage.removeItem with key k to remove the entry with k as the key.

Conclusion

To remove all session storage items with keys that match a certain pattern with JavaScript, we can loop through the keys of the items we want to remove and remove the entries with the keys.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *