// name found // Analysis if(cookieString.substring(i, i + name.length) == name) { i += (name.length + 1); if(cookieString.indexOf(";", i) < i) return unescape(cookieString.substring(i, cookieString.length)); else return unescape(cookieString.substring(i, cookieString.indexOf(";", i))); }This section of code is executed if the condition is met, signalling that the cookie was found. The substring() method is used to compare the name of the cookie with the string beginning at the index variable and continuing on for as many characters as there are letters in the name. When the code gets to the cookie, this section of code should provide an exact match.
If the cookie is found, the next step is to extract the value from the cookie. To accomplish this, the index variable, i, is moved forward to the end of the name, and then moved past the equals sign.
Because this is a general purpose function, we have to cater for situations where the cookie found is the only cookie, or the last cookie of the document, as well as when there are more cookies in the document.
The code uses the indexOf() method to seach for the next occurence of a semicolon. The indexOf() method accepts two arguments: the string to search for (';' in this case) and the position of the string to begin the search. In this case, we want to start from the beginning of the value string, which is indexed by the variable i.
The indexOf() method returns the index of the first occurence of the string if it is found, or -1 if it is not found. The example checks to see if the value returned from the indexOf() method is less than the start of the value string. In other words, if the string -- the semicolon -- is not found, the value returned will be -1, which is less than the index variable. In this case, the substring beginning at the index variable and ending at the last character of the string is returned.
However, if another cookie follows in the index string, it will be separated from the current cookie by a semicolon. In this case, the search for the index of the next semicolon will be greater than the index variable, and the code will return the string between the index variable and the semicolon.
Finally, the unescape() function is used to convert the encoded text back to ASCII (or plain) text.