Question

I have this code:

for(var i=0; i < localStorage.length; i++) {
   var subjects = [];

   var key, value;
   key = localStorage.key(i);
   value = localStorage.getItem(key);

   var keysplit = key.split(".");

   if(keysplit[keysplit.length] == "subj") {
       subjects.push(value);
   }

}

I am trying to select all the keys that have a .subj ending, but this does not seem to work. Any ideas?

Was it helpful?

Solution

The length property returns the number of items in the array, and as the index is zero based there is no item with that index.

Use length - 1 to get the last item:

if (keysplit[keysplit.length - 1] === "subj") {

OTHER TIPS

Other possibilities:

if(key.substr(key.lastIndexOf('.')) == ".subj")
//or
var suffix = '.subj';
if(key.lastIndexOf(suffix) == key.length - suffix.length)

See: lastIndexOf

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top