Is this the correct method for choosing elements with a ".subj" suffix?

Here is the code snippet I am using:

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 encountering an issue where my code is not correctly selecting all the keys that end with .subj. Any suggestions on how to fix this problem?

Answer №1

The length attribute provides the count of elements in the array, where indexing starts at zero meaning there is no element at that index.

To access the last item, simply use length - 1:

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

Answer №2

Here are some other options to consider:

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

For more information, check out: lastIndexOf

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating directly to a page in ReactJS and Redux without needing to login if a token is found in the local storage

Currently in the main component, it is set to automatically redirect to the Login page. However, I want to implement a check to see if a token is already stored in the local storage. If a token exists, I want the application to skip the Login page and dire ...

How can I ensure proper separation of concerns while incorporating JavaScript in HTML development?

Currently, I am diving into jQuery by delving into the world of jQuery in Action. In this book, there is a discussion about separation of concerns through the use of 'Unobtrusive JavaScript.' I understand the importance of keeping JavaScript-def ...

Working with Node.js and Redis: Managing multiple queries across various Redis databases using a single client connection

I'm new to Node.js and its asynchronous operations. My goal is to fetch data from different Redis databases. Here's a simple function I've created to retrieve a key from a Redis database: function get_key(client, key, db, callback) { i ...

What is the method for utilizing the value component as the key for the second component?

In my JSON data below: [{"id":19,"text":"A-Z CLI 19/03/2015"},{"id":36,"text":"Wavetel Retail1"},{"id":37,"text":"Wavetel A2Z Platinum"},{"id":38,"text":"Wavetel A2Z Gold"},{"id":40,"text":"mysql test2"},{"id":63,"text":"inbound test"},{"id":137,"text": ...

Is there a CSS equivalent of .live() in jQuery?

Is it possible to apply CSS styles to dynamically created elements? Let's take a look at a basic example of what I am trying to achieve: $(document).ready(function() { $('#container').html('<p id="hello">hello world</p&g ...

"The onkeydown event dynamically not triggering for children elements within a parent element that is contentEditable

Can anyone offer some insights into why this code isn't functioning as expected? My goal is to attach the listener to the children elements instead of the body so that I can later disable specific keystrokes, such as the return key. <!DOCTYPE html ...

Subtracting 25% from the width of the web browser

After spending some time trying to solve this issue by myself, I've decided to reach out for help here where I know I can get some great responses. I am looking to determine the dimensions of the browser window minus 25%. Specifically, I have a two-c ...

Converting a lengthy HTML document into numerous JPEGs (or any preferred image format)

I am working on a lengthy webpage that can be viewed as having 40 individual pages. Each "page" is separated by a horizontal rule () and has a fixed height of 860px. My goal is to convert each of these "pages" into JPG images automatically. Can anyone pr ...

Exploring the intricacies of Bower and enhancing dependency management

Currently, I am working on developing a project named myapp using angularJS along with Yeoman Generator. This project involves utilizing Bower to manage dependencies and Grunt to wiredep those dependencies into the index.html file (which essentially genera ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Unable to progress in an HTML5 Drag and Drop application

I am currently learning HTML5 and I have encountered an issue with a specific example. The code is running without errors, but the drag and drop functionality is not working as expected. I have included the code snippet below. Could you please review it fo ...

React Router: Navigating to a Route Becomes Problematic with useNavigate Hook

I am currently developing a React application that utilizes React Router for navigation purposes. One specific component named ShowNotes is causing some issues with the implementation of a "Delete" button, which is intended to redirect to the "/DeleteNotes ...

What is the best way to utilize .some() in determining if a specific property value is present within an array of objects?

I have an array filled with objects, each representing a individual heading to a movie theater. These objects include properties like Name, Age, and Hobby. If there is at least one person under 18 years old, the variable censor should be set to true. Desp ...

Using Express-session in the Internet Explorer browser

When configuring the express-session plugin, I follow this setup: var express = require('express'), session = require('express-session'), uuid = require('node-uuid'); var expiration_day = new Date('9/15/2015&apo ...

Transfer the value of a variable within the local scope to the dragstart event handler during the dynamic generation of an input element

After going through several similar questions, I couldn't find a solution that applies to my specific case. Here is the loop I am working with: $.each(data.modules, function(i, field) { let $li = $(`<li><div> Name: ${field.name}</div& ...

Using a parameter as a key index in JavaScript

Here's the structure of my Object festivals: Object {friday: Object} friday: Object amazon: Object band: Object Next, I've created a function called`newAct`: function newAct(band, date, startTime, endTime, stage){ var ...

Using MySQL and PHP, implementing a feature that generates lines on Google Maps by fetching coordinates from a database

I have an idea to develop a navigation application where I need to draw a line connecting two points stored in a Database. The line starts from the starting point, goes through a fixed point defined in the code, and ends at the destination point. To achi ...

Skip the "required" attribute in HTML forms for submission

Before submitting a form, I rely on the use of required for initial validation. <form action = "myform.php"> Foo: <input type = "text" name = "someField" required = "required"> <input type = "submit" value = "submit"> <input typ ...

Locate and retrieve user data from MongoDB

Let me provide some context. I am transmitting a post along with the username and what he shared with me is shown in the log. console.log(req.body.username); // 'username' My question is, how can I utilize mongodb to locate and display a user w ...

Determine whether a click event originated from within a child window

Currently, I am utilizing window.open to initiate a new window in javascript and my goal is to identify clicks made within the child window. Essentially, if a click event occurs in the child window, I aim to modify the parent window accordingly. I have a ...