Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

Tags:

I have 2 apps working together with localstorage and I was wondering how can I delete all the keys which start with note- and todo- . I know localstorage.clear() clears everything but thats not my aim.

Here is an example of what I have in my localstorage: enter image description here

Where I want to delete all the todo-* with a button click and all note-* with other button click using jquery.

Thanks alot

like image 493
jQuerybeast Avatar asked Sep 29 '11 02:09

jQuerybeast


People also ask

What is HTML5 local storage?

HTML5 local storage is a component of the Web storage application programming interface. It is a method by which Web pages locally store named key/value pairs inside a client's Web browser.

Can we use localStorage in HTML?

HTML web storage provides two objects for storing data on the client: window. localStorage - stores data with no expiration date.

How HTML5 is more powerful in terms of storage?

Consequently, HTML5 has greatly simplified the process of creating web applications. Thanks to HTML5, web pages can now store data locally on the user's browser, which eliminates the need for HTTP cookies. As a result, content can be delivered faster and more securely.

Does HTML5 support offline storage?

The local storage is a type of HTML5 offline storage that allows user string data to be saved synchronously in their browser. Information is kept in name and value pairs and not available between different browsers on the same device. Local storage can be used as an alternative to cookies.


2 Answers

Object.keys(localStorage)       .forEach(function(key){            if (/^todo-|^note-/.test(key)) {                localStorage.removeItem(key);            }        }); 
like image 95
Ghostoy Avatar answered Oct 27 '22 01:10

Ghostoy


I used a similar method to @Ghostoy , but I wanted to feed in a parameter, since I call this from several places in my code. I wasn't able to use my parameter name in a regular expression, so I just used substring instead.

function ClearSomeLocalStorage(startsWith) {     var myLength = startsWith.length;      Object.keys(localStorage)          .forEach(function(key){              if (key.substring(0,myLength) == startsWith) {                 localStorage.removeItem(key);              }          });  } 
like image 33
WEFX Avatar answered Oct 27 '22 01:10

WEFX