Which of these read cookie scripts would you recommend?

I’m cleaning up my folder Webstuff, and came across another read cookie javascript than I normally use. I wonder which one would actually be best, if at all, and why, or what the practical differences are:

function readCookie(name) {
    if (name == "") return "";
    var strCookie =" " + document.cookie;
    var idx = strCookie.indexOf(" " + name + "=");
    if (idx == -1) idx = strCookie.indexOf(";" + name + "=");
    if (idx == -1) return "";
    var idx1 = strCookie.indexOf(";", idx+1);
    if (idx1 == -1) idx1 = strCookie.length;
    return unescape(strCookie.substring(idx + name.length+2, idx1));
}

or

function readCookie(name) {
    var nameEQ = name + "=";
    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,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

They’re both unnecessarily clunky and the second fails to decode any escaped characters.

If you modify the cookie string you can use indexOf without looping:

function readCookie( cName )
{
  var nameIdx,
      cv = "",
      data = " " + ( document.cookie || "" ) + ";" ;

  if( ( nameIdx = data.indexOf( " " + cName + '=' ) ) != -1 )
    cv = data.substring( nameIdx += cName.length + 2, data.indexOf( ';', nameIdx ) );

  return decodeURIComponent( cv );
}

If you want a regex solution:

function readCookie( cName )
{
  var v;

  return decodeURIComponent( ( v = ( document.cookie || "" ).match( "(^|\\\\s)" + cName + "=([^;]+)" ) ) ? v[ 2 ] : "" );
}

That second one from the OP’s post has always been a favorite of mine. It comes from http://www.quirksmode.org/js/cookies.html which is where a developer specialised in finding and dealing with cross-browser issues.

Thanks, guys. At least now I know why they are so chunky and what they do exactly, which were my primary concerns.