How to Clear Local Storage JavaScript
There is a simple way of o resetting a browser's localStorage using its clear() method.
Just invoke the clear() of the Storage interface method, and it will clear the whole storage of all records for that specific domain:
<!DOCTYPE html>
<html>
<head>
<style>
body {
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h2>Create local storage items </h2>
<button onclick="createItems()">
Create local storage items
</button>
<h2>Display Items</h2>
<button onclick="displayItems()"> Display items</button>
<p id="show"></p>
<h2>Remove Items</h2>
<button onclick="deleteItems()"> Clear locak storage </button>
<h2>Display Items Again</h2>
<button onclick="displayItems()"> Display again </button>
<p id="demo"></p>
<script>
function createItems() {
// Set item in local storage.
localStorage.setItem("Welcome toW3Docs ", " ");
localStorage.setItem("Storage Clear Method ", " ");
}
function deleteItems() {
// Clear localStorage items
localStorage.clear();
}
function displayItems() {
let l, i;
// Display items
document.getElementById("show").innerHTML = "";
for(i = 0; i < localStorage.length; i++) {
res = localStorage.key(i);
document.getElementById("show").innerHTML += res;
}
}
</script>
</body>
</html>
If you want to remove a specific item or variable from the user's local storage, you can use the following:
localStorage.removeItem("name of localStorage variable or item to remove");
LocalStorage
LocalStorage and sessionStorage are web storage objects that allow developers to save key-value pairs in the browser. It is a type of web storage allowing JavaScript apps or sites to store and access data right in the browser without an expiration date which means that data stored in localStorage won't be cleared when the page is closed.