简体   繁体   中英

Clarification about the JavaScript getCookie function?

The getCookie function is first called in a checkCookie function as so:

var username=getCookie("username");

And this is the function:

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
  {
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

I'm lost on what is happening overall.. why do you split on ; , and mainly what is the reason for the the lines with x and y . The source is here . I appreciate any tips or advice.

The most effective way to get a cookie value is to use regular expressions.

function cookie_get(n){
  return (n=(document.cookie+';').match(new RegExp(n+'=.*;')))&&n[0].split(/=|;/)[1]
}

cookies are always stored as: key1=value1;key2=value2

so the split on ; is to read all the key-value pairs into the ARRcookies variable. Then, for each cookie, the key is read into x, and the value into y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM