Read a javascript cookie by name

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

I have set a cookie using

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

No

11条回答
  •  不知归路
    2020-12-05 07:17

    Use the RegExp constructor and multiple replacements to clarify the syntax:

    function getCook(cookiename) 
      {
      // Get name followed by anything except a semicolon
      var cookiestring=RegExp(cookiename+"=[^;]+").exec(document.cookie);
      // Return everything after the equal sign, or an empty string if the cookie name not found
      return decodeURIComponent(!!cookiestring ? cookiestring.toString().replace(/^[^=]+./,"") : "");
      }
    
    //Sample usage
    var cookieValue = getCook('MYBIGCOOKIE');
    

提交回复
热议问题