How to Clear or Reset Browser LocalStorage History in Javascript Full Tutorial For Beginners

 

Use this to clear localStorage:

localStorage.clear();

 

 

If you want to remove a specific Item or variable from the user’s local storage, you can use

localStorage.removeItem("name of localStorage variable you want to remove");

 

 

window.localStorage.clear(); //try this to clear all local storage

 

Here is a function that will allow you to remove all localStorage items with exceptions. You will need jQuery for this function. You can download the gist.

See also  Node.js Project to Extract Text From PDF File Using pdf-to-text Library in Javascript Full Tutorial For Beginners

You can call it like this

let clearStorageExcept = function(exceptions) {
  let keys = [];
  exceptions = [].concat(exceptions); // prevent undefined

  // get storage keys
  $.each(localStorage, (key) => {
    keys.push(key);
  });

  // loop through keys
  for (let i = ; i < keys.length; i++) {
    let key = keys[i];
    let deleteItem = true;

    // check if key excluded
    for (let j = ; j < exceptions.length; j++) {
      let exception = exceptions[j];
      if (key == exception) {
        deleteItem = false;
      }
    }

    // delete key
    if (deleteItem) {
      localStorage.removeItem(key);
    }
  }
};

 

If you want to clear all item you stored in localStorage then

localStorage.clear();

Use this for clear all stored key.

See also  jQuery AJAX Tutorial to Display Instagram Feed in Website Using Facebook Graph API Using HTML5 & Javascript Full Project For Beginners

If you want to clear/remove only specific key/value then you can use removeItem(key).

localStorage.removeItem('yourKey');

Leave a Reply