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)?
JavaScript
x
4
1
while (c.charAt(0) == ' ') {
2
c = c.substring(1);
3
}
4
This is the full code:
JavaScript
1
34
34
1
function setCookie(cname, cvalue, exdays) {
2
const d = new Date();
3
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
4
let expires = "expires="+d.toUTCString();
5
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
6
}
7
8
function getCookie(cname) {
9
let name = cname + "=";
10
let ca = document.cookie.split(';');
11
for(let i = 0; i < ca.length; i++) {
12
let c = ca[i];
13
while (c.charAt(0) == ' ') {
14
c = c.substring(1);
15
}
16
if (c.indexOf(name) == 0) {
17
return c.substring(name.length, c.length);
18
}
19
}
20
return "";
21
}
22
23
function checkCookie() {
24
let user = getCookie("username");
25
if (user != "") {
26
alert("Welcome again " + user);
27
} else {
28
user = prompt("Please enter your name:", "");
29
if (user != "" && user != null) {
30
setCookie("username", user, 365);
31
}
32
}
33
}
34
Advertisement
Answer
while loop use just remove first empty space;
JavaScript
1
10
10
1
for(let i = 0; i < ca.length; i++) {
2
let c = ca[i]; // example ' abde dfda'
3
while (c.charAt(0) == ' ') {
4
console.log('charAt =>',c.charAt(0))
5
console.log('subString =>',c.substring(1))
6
c = c.substring(1);
7
console.log('final c =>', c);
8
}
9
}
10
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