Js read cookie method summary
- 2020-03-30 04:12:24
- OfStack
This example summarizes the js method of reading cookies. Share with you for your reference. The specific implementation method is as follows:
In general, there are many methods for js to read cookies. The following instance function mainly USES the split function to split, and document.cookie gets all cookies and then USES for traversing all arrays to judge that if the cookie name is the same, then this cookie is what we are looking for.
Methods a
var acookie=document.cookie.split("; ");
function getck(sname)
{//Gets a single cookie
for(var i=0;i<acookie.length;i++){
var arr=acookie[i].split("=");
if(sname==arr[0]){
if(arr.length>1)
return unescape(arr[1]);
else
return "";}}
return "";
}
Method 2
function getcookie(objname){//Gets the value of the cookie with the specified name
var arrstr = document.cookie.split("; ");
for(var i = 0;i < arrstr.length;i ++){
var temp = arrstr[i].split("=");
if(temp[0] == objname) return unescape(temp[1]);
}
}
Methods three
function getcookie(cookiename){
var cookiestring = document.cookie;
var start = cookiestring.indexof(cookiename + '= ');
if (start == -1) //
could not be found
return null;
start += cookiename.length + 1;
var end = cookiestring.indexof( "; ", start);
if (end == -1) return unescape(cookiestring.substring(start));
return unescape(cookiestring.substring(start, end));
}
Methods four
function readcookie(name)
{
var cookievalue = "";
var search = name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexof(search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexof(";", offset);
if (end == -1) end = document.cookie.length;
cookievalue = unescape(document.cookie.substring(offset, end))
}
}
return cookievalue;
}