Get cookie by name

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

    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 + "=.[^;]*")
        var 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.

提交回复
热议问题