I need to set a cookie with javascript which I'm doing this with the following mand:
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
I need to set a cookie with javascript which I'm doing this with the following mand:
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
Share Improve this question edited Sep 9, 2014 at 14:36 maja asked Jun 27, 2012 at 17:19 majamaja 18.1k18 gold badges84 silver badges127 bronze badges2 Answers
Reset to default 4You 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
.
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.