Get cookie by name

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

    I would prefer using a single regular expression match on the cookie:

    window.getCookie = function(name) {
      var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
      if (match) return match[2];
    }
    

    OR Also we are able to use as a function , check below code.

    function check_cookie_name(name) 
        {
          var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
          if (match) {
            console.log(match[2]);
          }
          else{
               console.log('--something went wrong---');
          }
       }
    

    Improved thanks to Scott Jungwirth in the comments.

提交回复
热议问题