Quote:
Originally Posted by ABorrello
Is this the best way to find a cookie name and value, or is there an easier way.
By the way, every time I test this script, my page freezes
|
If you want to search, this topic has been covered zillions of times, although not always very well...
The essential problem is your misuse of substring, which expects to work with integer parameters, not strings.
The statement
Code:
if (str_parts[i].substring('','=')==tofindstr)
could be something like
Code:
if( str_parts[i].substring( 0, str_parts[i].indexOf( '=' ) ) == tofindstr )
although it is important to split on "; " not ";".
Here is an example of using the String.split approach and also a RegEx example:
Code:
function readCookie( cName ) /* Uses String.split */
{
var pairs = ( document.cookie || "" ).split( "; " ),
len = pairs.length,
offset;
for( var i = 0; i < len && ( offset = pairs[ i ].indexOf( cName + '=' ) ) != 0; i++ )
;
return i != len ? decodeURIComponent( pairs[ i ].substring( offset + cName.length + 1 ) ) : "" ;
}
function readCookie( cName ) /* Uses Regex */
{
var v;
return decodeURIComponent( ( v = ( document.cookie || "" ).match( "(^|\\s)" + cName + "=([^;$]+)" ) ) ? v[ 2 ] : "" );
}