Safely store Unicode characters in a CookieTag(s): Language


Use encodeURIComponent() when setting the cookie and decodeURIComponent() when retrieving it.

This is required with japanese characters for example.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<HTML><HEAD>
<SCRIPT>
function setstuffcookie() {
  document.cookie = "stuff=" + encodeURIComponent(document.getElementById('stuff').value);
}

function getcookie(cookiename) {
  var results = document.cookie.match ( '(^|;) ?' + cookiename + '=([^;]*)(;|$)' );
  if ( results )
    return ( decodeURIComponent(results[2] ) );
  else
    return null;
}
</SCRIPT>
</HEAD>

<BODY>
Testing cookie with Unicode letters
<input id="stuff" width=50 />

<button onclick="setstuffcookie()">Write stuff cookie</button>
<button onclick="alert(getcookie('stuff'))">Display stuff cookie</button>
</BODY>
</HTML>
Try it :

Testing cookie with Unicode letters :


blog comments powered by Disqus