user4737789
user4737789

Reputation:

Javascript set then display a cookie value

My problem seems to be easy but I can't make it work; I want to set a cookie variable called "splash" then display it (later I want use in IF clause) Here is my code :

<html>
   <head>
      <script type="text/javascript">
document.cookie =  "splash=" + encodeURIComponent("blue theme")
   var re = new RegExp(splash + "=([^;]+)");
    var value = re.exec(document.cookie);
    alert(value);
   </script>
   </head>
 <body>
 </body>
</html>

Upvotes: 0

Views: 208

Answers (2)

Vinie
Vinie

Reputation: 2993

Use Following function to set and get Cookie

function createCookie(name, value, days)
{
    if(days)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else
    {
        var expires = "";
    }
    var fixedName = '';
    name = fixedName + name;
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(name) 
{
   var value = "; " + document.cookie;
   var parts = value.split("; " + name + "=");
   if (parts.length == 2) return parts.pop().split(";").shift();
}
function eraseCookie(name) 
{
    createCookie(name, "", -1);
}

Upvotes: 0

grdaneault
grdaneault

Reputation: 840

You should change your regex to include splash as part of the quoted string. Even though spash is the variable you're using in the cookie, it does not automatically become a javascript variable.

document.cookie = "splash=" + encodeURIComponent("blue theme")
var re = new RegExp("splash=([^;]+)");
var theme = re.exec(document.cookie)[1];

re.exec returns an array. the first element is the entire matched string (including splash=). The second is your capture group (blue%20theme).

Upvotes: 1

Related Questions