How can I create and read a value from a cookie in JavaScript?
An improved version of the readCookie:
function readCookie( name )
{
var cookieParts = document.cookie.split( ';' )
, i = 0
, part
, part_data
, value
;
while( part = cookieParts[ i++ ] )
{
part_data = part.split( '=' );
if ( part_data.shift().replace(/\s/, '' ) === name )
{
value = part_data.shift();
break;
}
}
return value;
}
This should break as soon as you have found your cookie value and return its value. In my opinion very elegant with the double split.
The replace on the if-condition is a white space trim, to make sure it matches correctly