View Single Post
Old 12-16-2012, 04:10 PM   PM User | #2
Logic Ali
Regular Coder

 
Logic Ali's Avatar
 
Join Date: Sep 2010
Location: London
Posts: 959
Thanks: 0
Thanked 198 Times in 193 Posts
Logic Ali will become famous soon enoughLogic Ali will become famous soon enough
Quote:
Originally Posted by ABorrello View Post
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 ] : "" );
}
Logic Ali is offline   Reply With Quote