I was going through a tut on the internet about Cookies in JS. So, they told to use this function "getCookie" !
I used that ..... but I cannot understand the use of regular expressions ie using document.cookie.split !!
'cause as far as I know a cookie is just a small text file.
Is that a way of reading from the text file ?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">

    function getCookie(c_name) {
        var i;
        var x;
        var y;
        var 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);
            }
        }
    }

    function setCookie(c_name, value, exdays) {
        var exdate = new Date();
        exdate.setDate(exdate.getDate() + exdays);
        var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value;
    }

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

</script>
</head>
  <body onload="checkCookie()">
  </body>
</html>

:-/

Please help !

Recommended Answers

All 5 Replies

Yes, you have to search for the cookie you want inside all of the cookies you have.

@Twiss

Are all cookies stored in one text file ?

No, but the browser serves you all your cookies in a single string.

Ok....
and all separated by a ";" right ??

Is there a way I can see what is in a cookie ?
like for the cookie stored for the above program ????

Yes, that's what your function is for.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.