Get cookie by name

前端 未结 30 1387
野的像风
野的像风 2020-11-22 03:58

I have a getter to get the value from a cookie.

Now I have 2 cookies by the name shares= and by the name obligations= .

I want to

30条回答
  •  长情又很酷
    2020-11-22 04:40

    It seems to me you could split the cookie key-value pairs into an array and base your search on that:

    var obligations = getCookieData("obligations");
    

    Which runs the following:

    function getCookieData( name ) {
        var pairs = document.cookie.split("; "),
            count = pairs.length, parts; 
        while ( count-- ) {
            parts = pairs[count].split("=");
            if ( parts[0] === name )
                return parts[1];
        }
        return false;
    }
    

    Fiddle: http://jsfiddle.net/qFmPc/

    Or possibly even the following:

    function getCookieData( name ) {
        var patrn = new RegExp( "^" + name + "=(.*?);" ),
            patr2 = new RegExp( " " + name + "=(.*?);" );
        if ( match = (document.cookie.match(patrn) || document.cookie.match(patr2)) )
            return match[1];
        return false;
    }
    

提交回复
热议问题