Home > Back-end >  JavaScript get cookies function
JavaScript get cookies function

Time:06-18

I've been learning on how to get Cookies from a web page. Below is the code extracted from w3schools.com. I am not sure why they used this line of code in the getCookies(cname) function as shown below. Why should there be a blank space at the start of every string in the array "ca"? And why should we take c.substring(1)?

while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }

This is the full code:

function setCookie(cname, cvalue, exdays) {
  const d = new Date();
  d.setTime(d.getTime()   (exdays * 24 * 60 * 60 * 1000));
  let expires = "expires=" d.toUTCString();
  document.cookie = cname   "="   cvalue   ";"   expires   ";path=/";
}

function getCookie(cname) {
  let name = cname   "=";
  let ca = document.cookie.split(';');
  for(let i = 0; i < ca.length; i  ) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  let user = getCookie("username");
  if (user != "") {
    alert("Welcome again "   user);
  } else {
    user = prompt("Please enter your name:", "");
    if (user != "" && user != null) {
      setCookie("username", user, 365);
    }
  }
}

CodePudding user response:

while loop use just remove first empty space;

for(let i = 0; i < ca.length; i  ) {
let c = ca[i]; // example ' abde dfda'
while (c.charAt(0) == ' ') {
  console.log('charAt =>',c.charAt(0))
  console.log('subString =>',c.substring(1))
  c = c.substring(1);
  console.log('final c =>', c);
}
}

enter image description here

cookie first char is ' ' value then removing while loop by c.substring(1)
example
    c = '  alertDialog=yes' that means c.chartAt(0) = ' ' ok
while (' ' == ' ') condition true
then
    c set c = 'alertDialog=yes'
    then 2nd loop false
  • Related