Get cookie by name

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

    use a cookie getting script:

    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }
    

    then call it:

    var value = readCookie('obligations');
    

    i stole the code above from quirksmode cookies page. you should read it.

    0 讨论(0)
  • 2020-11-22 04:18

    set by javascript

    document.cookie = 'cookiename=tesing';
    

    get by jquery with the jquery-cookie plugin

    var value = $.cookie("cookiename");
    
    alert(value);
    
    0 讨论(0)
  • 2020-11-22 04:19

    If you use jQuery I recommend you to use this plugin:

    https://github.com/carhartl/jquery-cookie
    https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

    <script type="text/javascript"
     src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js">
    

    So you can read cookie like this:

    var value = $.cookie("obligations");
    

    Also you can write cookie:

    $.cookie('obligations', 'new_value');
    $.cookie('obligations', 'new_value', { expires: 14, path: '/' });
    

    Delete cookie:

    $.removeCookie('obligations');
    
    0 讨论(0)
  • 2020-11-22 04:20

    One approach, which avoids iterating over an array, would be:

    function getCookie(name) {
      const value = `; ${document.cookie}`;
      const parts = value.split(`; ${name}=`);
      if (parts.length === 2) return parts.pop().split(';').shift();
    }
    

    Walkthrough

    Splitting a string by token will produce either, an array with one string (same value), in case token does not exist in a string, or an array with two strings , in case token is found in a string .

    The first (left) element is string of what was before the token, and the second one (right) is what is string of what was after the token.

    (NOTE: in case string starts with a token, first element is an empty string)

    Considering that cookies are stored as follows:

    "{name}={value}; {name}={value}; ..."
    

    in order to retrieve specific cookie value, we just need to get string that is after "; {name}=" and before next ";". Before we do any processing, we prepend the cookies string with "; ", so that every cookie name, including the first one, is enclosed with "; " and "=":

    "; {name}={value}; {name}={value}; ..."
    

    Now, we can first split by "; {name}=", and if token is found in a cookie string (i.e. we have two elements), we will end up with second element being a string that begins with our cookie value. Then we pull that out from an array (i.e. pop), and repeat the same process, but now with ";" as a token, but this time pulling out the left string (i.e. shift) to get the actual token value.

    0 讨论(0)
  • 2020-11-22 04:21

    My one linear function to get the value cookie by its key.

    cookie = key=>((new RegExp((key || '=')+'=(.*?); ','gm')).exec(document.cookie+'; ') ||['',null])[1]
    

    Call cookie function as

    cookie('some-key')
    
    0 讨论(0)
  • 2020-11-22 04:21

    always works well:

    function getCookie(cname) {
        var name = cname + "=",
            ca = document.cookie.split(';'),
            i,
            c,
            ca_length = ca.length;
        for (i = 0; i < ca_length; i += 1) {
            c = ca[i];
            while (c.charAt(0) === ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) !== -1) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }
    
    function setCookie(variable, value, expires_seconds) {
        var d = new Date();
        d = new Date(d.getTime() + 1000 * expires_seconds);
        document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
    }
    

    No requirements for jQuery or anything. Pure old good JavaScript.

    0 讨论(0)
提交回复
热议问题