RBT
RBT

Reputation: 25945

Why browser prepends a space while inserting key value pairs in cookies through javascript

I wrote a very simple javascript code to insert cookies :

// setting the cookie value
function setCookie(cookieName, cookieValue) {
        document.cookie ='prasik=bihari';
        document.cookie ='pintu=tiwari';
        document.cookie = cookieName + "=" + cookieValue;
        document.cookie ='mykey=myvalue';
    }


// retrieving the cookie value
function getCookie(cookieName)
{
    var cookies = document.cookie.split(";");
    //printing the cookie array on console in developer tools
    console.debug(cookies);
    for (var i = 0; i < cookies.length; i++) {
        var cookie = cookies[i];
        var index = cookie.indexOf("=");
        var key = cookie.substr(0, index);
        var val = cookie.substr(index + 1);
        if (key == cookieName)
        return val;
    }
}

setCookie('firstName', 'Glenn');
var firstName = getCookie('pintu');
//this prints undefined as it fails to get the key 'pintu' which has been converted to ' pintu'
console.debug(firstName);

firstName = getCookie(' pintu');
//prints the correct value
console.debug(firstName);

Inside the getCookie method whenever I split the cookies using ; character then developer tools shows me a space before the name of all the keys in the array except the first one:

enter image description here

So I fail to fetch the cookie value with the actual key 'pintu' I had user while inserting the cookie. Instead when I use ' pintu', I get the value. Can someone explain this strange behavior or I'm making a mistake in my program?

P.S. I'm getting this behavior on Chrome as well as firefox.

Upvotes: 2

Views: 541

Answers (1)

kaelwebdev
kaelwebdev

Reputation: 31

when you do document.cookie more times a space is added. so you must make the separation including that space.

document.cookie.split("; ");

Upvotes: 1

Related Questions