Read a javascript cookie by name

后端 未结 11 999
盖世英雄少女心
盖世英雄少女心 2020-12-05 06:50

I have set a cookie using

document.cookie = 
    \'MYBIGCOOKIE=\' + value + 
    \'; expires=\' + now.toGMTString() + 
    \'; path=/\';

No

11条回答
  •  -上瘾入骨i
    2020-12-05 07:17

    The simplest way to read a cookie I can think is using Regexp like this:

    **Replace COOKIE_NAME with the name of your cookie.

    document.cookie.match(/COOKIE_NAME=([^;]*);/)[1]
    

    How does it work?

    Cookies are stored in document.cookie like this: cookieName=cookieValue;cookieName2=cookieValue2;.....

    The regex searches the whole cookie string for literaly "COOKIE_NAME=" and captures anything after it that is not a semicolon until it actually finds a semicolon;

    Then we use [1] to get the second item from array, which is the captured group.

提交回复
热议问题