Categories
JavaScript Answers

How to replace local storage data for an already existing key with JavaScript?

Spread the love

Sometimes, we want to replace local storage data for an already existing key with JavaScript.

In this article, we’ll look at how to replace local storage data for an already existing key with JavaScript.

How to replace local storage data for an already existing key with JavaScript?

To replace local storage data for an already existing key with JavaScript, we can get the value with getItem, change the returned value, and then save it with setItem.

For instance, we write:

localStorage.setItem('string', 'foo')
const s = localStorage.getItem('string')
localStorage.setItem('string', `${s}bar`)

We call setItem with the key and value to add an entry with key string and value 'foo'.

Then we get the item with key string with getitem.

Next, we call setItem again with the same key and a different value to save the value for the same key.

Conclusion

To replace local storage data for an already existing key with JavaScript, we can get the value with getItem, change the returned value, and then save it with setItem.

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 *