Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

indexOf() in javascript

Okay so i have started learning javascript from the book Beginning Javascript 5th ed, just confused by a js 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 question is how does the indexOf operator works here( i know how it works and used it previously) ?? The above program is defined below by the book which goes as :

The first task of the function is to get the document.cookie string and store it in the value variable

var value = document.cookie;

Next, you need to find out where the cookie with the name passed as a parameter to the function is within the value string. You use the inde x Of() method of the String object to find this information, as shown in the following line:

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

The method will return either the character position where the individual cookie is found or ‐1 if no such name, and therefore no such cookie, exists. You search on " " + name + "=" so that you don’inadvertently find cookie names or values containing the name that you require. For example, if you have xFoo, Foo, and yFoo as cookie names, a search for Foo without a space in front would match xFoo first, which is not what you want!

What the just just happened here?? How did they achieve the location of the name using indexOf() ?? please explain ? I couldn't understand the xfoo,foo,yfoo example ?? Looking for a simpler example.

like image 877
Syndicate Avatar asked Mar 23 '26 04:03

Syndicate


1 Answers

document.cookie contains a string like cookiename=cookievalue

indexOf is getting the position of the begining of the value part of the cookie

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

That allows you to use that number to get the value portion of the string with substring()

like image 98
I wrestled a bear once. Avatar answered Mar 24 '26 19:03

I wrestled a bear once.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!