Read cookie by name in JavaScript

Description

The following code shows how to read cookie by name.

Example


<html>
<body>
<script language="JavaScript">
var cookies = document.cookie;<!--  w w  w  . j a v  a 2s .  c o m-->
function readCookie(name) {
var start = cookies.indexOf(name + "=");
if (start == -1){
document.writeln("Cookie not found");
}
start = cookies.indexOf("=", start) + 1;
var end = cookies.indexOf(";", start);
if (end == -1){
end = cookies.length;
}
var value = unescape(cookies.substring(start, end));
if(value == null){
document.writeln("No cookie found");
} else{
document.writeln("Cookie value is: " + value);
}
}
readCookie("java2s.com");

</script>
</body>
</html>

Click to view the demo

The code above generates the following result.

Read cookie by name in JavaScript
Home »
  Javascript Tutorial »
    Document »
      Cookie
Javascript Tutorial Cookie
Add date type value as cookie value in Java...
Read cookie by name in JavaScript
Read cookie value and fill the value to for...
Read value from a input text field and use ...
Set cookie with additional items separated ...
Set the cookies associated with the documen...
Update the cookies associated with the docu...
read the cookies associated with the docume...