1

sorry for a question to ask... Below is the tutorial of getCookie code from W3C School

Would someone teach me what is the function of while (c.charAt(0)==' ') c = c.substring(1); , and since it is while loop, why won't it keep repeating and stuck there?

Thanks...

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

   }
3
  • while the first character is an empty space, remove the first character. It's trying to trim empty space of the front of a string Commented Mar 21, 2016 at 17:01
  • 4
    "W3C School" — W3Schools is a purveyor of low quality tutorials. The W3C is a standards organisation. They are not the same organisation and you should avoid confusing them. Commented Mar 21, 2016 at 17:03
  • Thanks guys! I got the point. Commented Mar 21, 2016 at 17:15

1 Answer 1

2

what is the function of while (c.charAt(0)==' ') c = c.substring(1);

It removes spaces at the front of c.

since it is while loop, why won't it keep repeating and stuck there?

while loops only repeat while the value is true. You can't have a string made up of infinite spaces.

Sign up to request clarification or add additional context in comments.

2 Comments

@ssube — It will remove multiple spaces. It is a poor version of trim (which removes multiple spaces).
please can any one tell me if there any problem to replace the function in the question with this , function getCokkie(cookie) { let decodedCookie = decodeURIComponent(document.cookie); let cookieslist = decodedCookie.split(cookie+"="); if (cookieslist.length > 1) { return cookieslist[1].split(";")[0].trim(); } else { return ""; } }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.