Skip to content

Commit e9f8bd0

Browse files
Encode and decode cookie special characters using the UTF-8 hex encoding
1 parent 19e479c commit e9f8bd0

2 files changed

Lines changed: 27 additions & 6 deletions

File tree

‎src/js.cookie.js‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,19 @@
1717
window.Cookies = factory();
1818
}
1919
}(function () {
20-
function encode(s) {
21-
return s
20+
function encode(value) {
21+
return value
22+
.replace(/,/, '%2C')
23+
.replace(/;/, '%3B')
24+
.replace(/ /, '%20')
2225
.replace(/"/g, '%22');
2326
}
2427

25-
function decode(s) {
26-
return s
28+
function decode(value) {
29+
return value
30+
.replace(/%2C/, ',')
31+
.replace(/%3B/, ';')
32+
.replace(/%20/, ' ')
2733
.replace(/%22/g, '"');
2834
}
2935

‎test/tests.js‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -285,8 +285,23 @@ test('json = true', function () {
285285
test('Quote as the first character in the cookie value', function () {
286286
expect(1);
287287
Cookies.set('c', '"');
288-
var actual = Cookies.get('c');
289-
strictEqual(actual, '"', 'should read the quote value');
288+
strictEqual(Cookies.get('c'), '"', 'should handle the quote character');
289+
});
290+
291+
test('RFC 6265 special characters', function () {
292+
expect(4);
293+
294+
Cookies.set('whitespace', ' ');
295+
strictEqual(Cookies.get('whitespace'), ' ', 'should handle the whitespace character');
296+
297+
Cookies.set('comma', ',');
298+
strictEqual(Cookies.get('comma'), ',', 'should handle the comma character');
299+
300+
Cookies.set('semicolon', ';');
301+
strictEqual(Cookies.get('semicolon'), ';', 'should handle the semicolon character');
302+
303+
Cookies.set('backslash', '\\');
304+
strictEqual(Cookies.get('backslash'), '\\', 'should handle the backslash character');
290305
});
291306

292307
module('removeCookie', lifecycle);

0 commit comments

Comments
 (0)