Skip to content

Commit 1208729

Browse files
Global replace and DRY
1 parent e9f8bd0 commit 1208729

2 files changed

Lines changed: 18 additions & 11 deletions

File tree

‎src/js.cookie.js‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,24 @@
1717
window.Cookies = factory();
1818
}
1919
}(function () {
20+
var chars = {
21+
',': '%2C',
22+
';': '%3B',
23+
' ': '%20',
24+
'"': '%22'
25+
};
2026
function encode(value) {
21-
return value
22-
.replace(/,/, '%2C')
23-
.replace(/;/, '%3B')
24-
.replace(/ /, '%20')
25-
.replace(/"/g, '%22');
27+
for (var character in chars) {
28+
value = value.replace(new RegExp(character, 'g'), chars[character]);
29+
}
30+
return value;
2631
}
2732

2833
function decode(value) {
29-
return value
30-
.replace(/%2C/, ',')
31-
.replace(/%3B/, ';')
32-
.replace(/%20/, ' ')
33-
.replace(/%22/g, '"');
34+
for (var character in chars) {
35+
value = value.replace(new RegExp(chars[character], 'g'), character);
36+
}
37+
return value;
3438
}
3539

3640
function parseCookieValue(value) {

‎test/tests.js‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ test('Quote as the first character in the cookie value', function () {
289289
});
290290

291291
test('RFC 6265 special characters', function () {
292-
expect(4);
292+
expect(5);
293293

294294
Cookies.set('whitespace', ' ');
295295
strictEqual(Cookies.get('whitespace'), ' ', 'should handle the whitespace character');
@@ -302,6 +302,9 @@ test('RFC 6265 special characters', function () {
302302

303303
Cookies.set('backslash', '\\');
304304
strictEqual(Cookies.get('backslash'), '\\', 'should handle the backslash character');
305+
306+
Cookies.set('multiple', '" ,;\\" ,;\\');
307+
strictEqual(Cookies.get('multiple'), '" ,;\\" ,;\\', 'should handle multiple special characters');
305308
});
306309

307310
module('removeCookie', lifecycle);

0 commit comments

Comments
 (0)