4

I need to set a cookie with javascript which I'm doing this with the following command:

document.cookie = name+"="+value;

My problem is that value is a string, which can contain any unicode-character.

Is there a function which automatically replaces special characters (like ;) - and if not, which characters are forbidden?

Something like the "encodeURIComponent()"-Function for Get-Parameters would be perfect

maja
  • 14,242
  • 14
  • 72
  • 106

2 Answers2

4

You should use window.escape.

The escape() method converts special characters (any characters that are not regular text or numbers) into hexadecimal characters, which is especially necessary for setting the values of cookies. Also useful when passing name=value pairs in the URL of a GET request, or an AJAX GET/POST request.

It also has window.unescape counterpart.

Upd. It may make some sense to use base64 encoding/decoding prior to escaping in order not to suffer that much from unicode characters expenditure by window.encode.

Community
  • 1
  • 1
Li0liQ
  • 10,730
  • 32
  • 52
  • I have now a further problem: The size of my Cookie is >4kB --> I can't store it (This functions expands the content dramatically) – maja Jun 27 '12 at 18:14
  • You could, for instance, get base64 of your values instead before putting them in a cookie - should take less space than encode result. See http://stackoverflow.com/questions/246801/how-can-you-encode-to-base64-using-javascript#246813 – Li0liQ Jun 27 '12 at 18:51
1

Why not use a robust cookie library to handle cookies?

$.cookie('key', value, { expires: 365 });

Browsers limit cookies to 4 kB. If you need to store more than 4 kB on the client, you should use local storage.

Community
  • 1
  • 1
josh3736
  • 124,335
  • 26
  • 203
  • 248
  • 1
    I only need cookies for a small feature, and I don't want to include a complete jquery-plugin. This would be an overkill – maja Jun 27 '12 at 18:04
  • @user1421312: You'll notice the plugin is 0.4 kB minified & gzipped -- hardly overkill. This is a case where it's a good idea to just use a library so you can spend your time on more valuable things. Also, cookies are limited to 4kB. See edits about storing more than that. – josh3736 Jun 27 '12 at 18:23