Get cookie by name

前端 未结 30 1830
野的像风
野的像风 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:29

    A functional approach to find existing cookies. It returns an array, so it supports multiple occurrences of the same name. It doesn't support partial key matching, but it's trivial to replace the === in the filter with a regex.

    function getCookie(needle) {
        return document.cookie.split(';').map(function(cookiestring) {
            cs = cookiestring.trim().split('=');
    
            if(cs.length === 2) {
                return {'name' : cs[0], 'value' : cs[1]};
            } else {
                return {'name' : '', 'value' : ''};
            }
        })
        .filter(function(cookieObject) { 
            return (cookieObject.name === needle);
        });
    }
    

提交回复
热议问题