Get cookie by name

2018-12-31 10:14发布

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 make this getter only to get the values from the obligations cookie.

How do I do this? So the 'for' splits the data into separate values and puts it in an array.

 function getCookie1() {
// What do I have to add here to look only in the "obligations=" cookie? 
// Because now it searches all the cookies.

    var elements = document.cookie.split('=');
    var obligations= elements[1].split('%');
    for (var i = 0; i < obligations.length - 1; i++) {
        var tmp = obligations[i].split('$');
        addProduct1(tmp[0], tmp[1], tmp[2], tmp[3]);
    }
 }

30条回答
公子世无双
2楼-- · 2018-12-31 11:01

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);
    });
}
查看更多
余生请多指教
3楼-- · 2018-12-31 11:02

kirlich gave a good solution. However, it fails when there are two cookie values with similar names, here is a simple fix for this situation:

function getCookie(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length >= 2) return parts.pop().split(";").shift();
}
查看更多
步步皆殇っ
4楼-- · 2018-12-31 11:03

You can use js-cookie library to get and set JavaScript cookies.

Include to your HTML:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

To create a Cookie:

Cookies.set('name', 'value');

To read a Cookie:

Cookies.get('name'); // => 'value'
查看更多
低头抚发
5楼-- · 2018-12-31 11:04

I like to use a closure for getting cookie values by name. The closure below will allow you to get a cookie value by name but will only parse the cookie string if it has been updated.

You can retrieve the value of a cookie with the following:

var foo = cookies.get( "bar" );

Code:

var cookies = ( function() {
    var cookieString = null;
    var cookieArray = [];

    function getValOf( name ) {
        if ( newCookies() ) {
            parseCookieString()
        }
        return cookieArray[ name ];
    }

    // Check if new cookies have been added
    function newCookies() {
        return cookieString === document.cookie;
    }

    function parseCookieString() {
        cookieString = document.cookie;

        // Separate cookies
        var cookies = cookieString.split( ";" );

        // Empty previous cookies
        cookieArray = [];

        // Update cookieArray with new name-value pairs
        for ( var i in cookies ) {

            // Separate name and value
            var nameVal = cookies[ i ].split( "=" );
            var name = nameVal[ 0 ].trim();
            var value = nameVal[ 1 ].trim();

            // Add cookie name value pair to dictionary
            cookieArray[ name ] = value;
        }
    }

    return {

        /**
         * Returns value or undefined
         */
        get: function( name ) {
            return getValOf( name );
        }  
    };
})();
查看更多
看风景的人
6楼-- · 2018-12-31 11:06

I have modified the function that Jonathan provided here, by using regular expression you can get a cookie value by its name like this:

function getCookie(name){
    var pattern = RegExp(name + "=.[^;]*")
    matched = document.cookie.match(pattern)
    if(matched){
        var cookie = matched[0].split('=')
        return cookie[1]
    }
    return false
}

If it returns empty string it means that the cookie exists but has no value, if it returns false then the cookie doesn't exist. I hope this helps.

查看更多
千与千寻千般痛.
7楼-- · 2018-12-31 11:11

Following function will return a key-value pair of the required cookie, where key is the cookie name and value will be the value of the cookie.

/**
 * Returns cookie key-value pair
 */
var getCookieByName = function(name) {
    var result = ['-1','-1'];
    if(name) {
        var cookieList = document.cookie.split(';');
        result = $.grep(cookieList,function(cookie) { 
            cookie = cookie.split('=')[0];
            return cookie == name;
        });
    }
    return result;
};
查看更多
登录 后发表回答