Can anyone tell me how to count the number of Strings present in localStorage and not the number of characters in it. I wrote localStorage.getItem('id').length to see how many numbers of Strings are being saved, but it doesn't count the number of Strings present in "id". It just counts the number of characters present in it. For example, this (["A","Roshan"]) are the Strings which are being saved in localStorage and when I use .length method, it should show the result as 2 and not 14. Whatever it may be, here are the codes where you can see how I save it in localStorage
var newName=document.getElementById('name').value;
if (localStorage.getItem('id') == null)
{
localStorage.setItem('id', '[]');
}
var old_names = JSON.parse(localStorage.getItem('id'));
old_names.push(newName);
localStorage.setItem('id', JSON.stringify(old_names));
CodePudding user response:
sample code
<p id="counter"> names counter : <span>0</span></p>
<p>
name : <input type="text" id="name" value="">
<button id="bt-add-name">add</button>
</p>
const
names_Storage = JSON.parse(localStorage.getItem('names') || '[]')
, e_counter = document.querySelector('#counter span')
, e_name = document.querySelector('#name')
;
e_counter.textContent = names_Storage.length
document.querySelector('#bt-add-name').onclick = e =>
{
let newName = e_name.value.trim()
if (newName)
{
names_Storage.push( newName )
e_counter.textContent = names_Storage.length
localStorage.setItem('names', JSON.stringify(names_Storage))
e_name.value = ''
e_name.focus()
}
}
CodePudding user response:
const ids = ['1','2','3'] // user ids
//set the ids inside local storage
localStorage.setItem('id', JSON.stringify(ids))
//get the ids back from local storage
if('id' in localStorage){
const ids = JSON.parse(localStorage.getItem('id'))
console.log(`total ids in local storage ${ids.length}`)
}
