How do I create and read a value from cookie?

前端 未结 19 1618
梦如初夏
梦如初夏 2020-11-21 04:42

How can I create and read a value from a cookie in JavaScript?

19条回答
  •  执笔经年
    2020-11-21 05:04

    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

提交回复
热议问题