Using indexOf() in JavaScript

Recently, I delved into learning JavaScript through the guide of Beginning Javascript 5th edition. However, I am stumped by a perplexing JavaScript script

function getCookieValue(name) {
var value = document.cookie;
var cookieStartsAt = value.indexOf(" " + name + "=");
if (cookieStartsAt == -1) {
    cookieStartsAt = value.indexOf(name + "=");
}
if (cookieStartsAt == -1) {
    value = null;
} else {
    cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
    var cookieEndsAt = value.indexOf(";", cookieStartsAt);
    if (cookieEndsAt == -1) {
        cookieEndsAt = value.length;
    }
    value = unescape(value.substring(cookieStartsAt,
       cookieEndsAt));
}
return value;}

My query pertains to the inner workings of the indexOf operator in this scenario (despite my prior understanding and use of it). The above snippet is explicated further in the book as follows:

The primary function of this code is to extract the document.cookie string and save it in the 'value' variable

var value = document.cookie;

Subsequently, the aim shifts to locating the desired cookie by using the name passed as a parameter to the function within the 'value' string. This is achieved through the indexOf() method of the String object, demonstrated in the ensuing line:

var cookieStartsAt = value.indexOf(" " + name + "=");

This method will either return the position where the specified cookie is found, or -1 if no such name (and thus, no cookie) exists. The inclusion of " " + name + "=" ensures that unintended matches are avoided. For instance, with cookie names like xFoo, Foo, and yFoo, a search for Foo without a space upfront might erroneously match xFoo first. This distinction is crucial!

What is the logic behind the indexOf() method in this context?? How does it pinpoint the location of the name? Can someone simplify the xFoo, Foo, yFoo example? I'm in need of a more straightforward illustration.

Answer №1

The document.cookie variable stores a string in the format of cookiename=cookievalue.

The indexOf method is used to find the position of the beginning of the value part of the cookie.

var cookieStartsAt = value.indexOf("cookiename=");

This number can then be used to extract the value portion of the string using the substring method.

Answer №2

Beneficial Implementation of indexOf with starting position

function IndexLocation(input_string, target /*string*/, starting_pos=0) /*int*/ {
 if (starting_pos<0) {starting_pos=0;}
 var portion=input_string.substr(starting_pos);
 var position=portion.indexOf(target);
 if (position>=0) { return position+starting_pos;} else {return -1;}
}

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

Toggle visibility

Seeking a unique example of a div SHOW / HIDE functionality where multiple divs are populated within the main container. Specifically looking to display new paragraphs or topics of text. I have experience with standard show/hide techniques for collapsing ...

Tips for receiving notifications when the Collapsible collapses

I'm having trouble figuring out how to receive notifications when the Collapsible is expanded and collapsed. Currently, I am not receiving any type of notification. Any suggestions on how to make this work? Below is my code: --Imported jQuery < ...

How can you save the output of console.log in JavaScript to a variable and then use that variable in HTML?

Here is the code snippet I've been working on. The first part consists of JavaScript code, and the second part includes HTML. $('#table').on('check.bs.table', function (e, row) { checkedRows.push({First: row.fname, Second: row ...

By utilizing // within the source of a <script>, one can efficiently reference external files without specifying the

Curious if anyone has come across any evidence, proof, or firsthand accounts of utilizing the traditional http/https JavaScript <script> hack: <script src="//someserver.com/js/script.js"></script> Have you faced any problems with this m ...

Having trouble accessing the `then` property of undefined while utilizing Promise.all()?

An issue has occurred where the property 'then' of undefined cannot be read: getAll(id).then((resp) => {...} ... export function getAll(id){ all([getOne(id), getTwo(id)]); } ... export all(){ return Promise.all([...arg]) } I' ...

Switch classes according to scrolling levels

My webpage consists of multiple sections, each occupying the full height and width of the screen and containing an image. As visitors scroll through the page, the image in the current section comes into view while the image in the previous section disappe ...

Issues persist with Ajax form submissions; the submitted data never seems to go through

I have encountered variations of this issue multiple times, but despite analyzing numerous examples, I am unable to determine why my code is not functioning properly. <script> $('document').ready(function(){ $('datafixForm' ...

Error occurred during Apple Login using Next_Auth: OAuthCallback issue

Attempting to log in with Apple using NextAuth. Authentication is successful, but it redirects to /?error=OAuthCallback. The URL being used is: https://appleid.apple.com/auth/authorize?client_id=com.wheeleasy.org&scope=name%20email&response_type= ...

What is causing the error to appear in the Android web-view when using vue.js?

During the development of my web app using Vue.js, I encountered a strange issue where everything was functioning correctly in desktop browsers but not on mobile devices. To troubleshoot this problem, I decided to install an Android emulator and use remote ...

Retrieving a value using forEach in protractor - Dealing with closures

I am facing an issue with the helper code below, as it is not returning the correct number of occurrences of a string. this.getActualFilteredStatusCount = function(strFilter){ return this.getTotalRows().then(function(count){ var totalCount = ...

Send information to the next route using Vue

Within my Vue frontend, there is a method called `moveToOrder` which asynchronously communicates with the backend to process a move from the cart collection to the orders collection: methods:{ async moveToOrder() { const res = await this.$axios.g ...

Unable to associate Slider values with TextFields in MaterialUI

Currently, I am trying to create a slide with 2 markers to indicate a price range and interact with it on the slide. Although I have linked the input with the slider, the connection from the slider to the input is not functioning properly. My attempt was t ...

Transitioning from webpack to vite with Vue.js for a Chrome extension development project

I am currently developing a Chrome extension using Vue.js. I have a project ready to start with, but it is set up with webpack. Within webpack, I have multiple entry points that result in the generation of HTML files and others with JavaScript only. Whil ...

Loop through a JSON object using a sequence of setTimeout() functions

After running another function, I have retrieved a JSON object stored in the variable 'json_result'. My objective is to log each individual JSON part (e.g. json_result[i]) after waiting for 5 seconds. Here was my initial attempt: for (let key ...

Error: The call stack has reached the maximum size limit in nodejs and reactjs

When I attempt to submit the token received from my registration using the code snippet below, I encounter an error stating "maximum call stack exceeded." exports.activationController = (req, res) => { const { token } = req.body; exports.activation ...

When the onClick event is triggered, my intention is to dynamically insert a new

I'm having trouble adding a new row on each click, as my code keeps replacing the existing row. I attempted moving the if statement outside the addTable function, but it didn't work as expected. I've tried multiple solutions without succes ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...

The JQuery function assigning a value of 0 to the selectedIndex property is not functioning properly across all selected fields

<select name="wpcf-others" id="abc" class="myzebra-control myzebra-select"> <option value="wpcf-field123">General Work Jobs</option> <option value="wpcf-fields--1">Journalist/Editors Jobs</option> <option value="wpcf-4868b8 ...

Update a particular class following an AJAX POST request in JavaScript

After conducting extensive research, I have come here seeking your assistance with a particular issue: I am using a comment system with multiple forms on the same page (utilizing FOSCommentBundle in Symfony). My goal is to be able to post comments via Aja ...