Posted By

devnull69 on 07/01/11


Tagged

cookie trim


Versions (?)

Get and Set Cookie


 / Published in: JavaScript
 

  1. function Trim(strValue) {
  2. return strValue.replace(/^\s+|\s+$/g, '');
  3. }
  4.  
  5. function getCookie(key) {
  6. var result = false;
  7. if(document.cookie) {
  8. var mycookieArray = document.cookie.split(';');
  9. for(i=0; i<mycookieArray.length; i++) {
  10. var mykeyValue = mycookieArray[i].split('=');
  11. if(Trim(mykeyValue[0]) == key) result = mykeyValue[1];
  12. }
  13. }
  14. return result;
  15. }
  16.  
  17. function setCookie(key, value, hoursExpire) {
  18. var ablauf = new Date();
  19. var expireTime = ablauf.getTime() + (hoursExpire * 60 * 60 * 1000);
  20. ablauf.setTime(expireTime);
  21. document.cookie = key + "=" + value + "; expires=" + ablauf.toGMTString();
  22. }
  23.  
  24. var mycookie = getCookie('meincookie');
  25. if(!mycookie) {
  26. // do whatever you want if the cookie is not set
  27. setCookie('meincookie', 'true', 24);
  28. } else {
  29. // do whatever you want if the cookie is set
  30. // mycookie contains the cookie value
  31. }

Report this snippet  

You need to login to post a comment.