Skip to content

Commit d0b9d59

Browse files
author
GrayYoung
committed
Format data
1 parent f3d7fe5 commit d0b9d59

3 files changed

Lines changed: 57 additions & 4 deletions

File tree

dist/jquery.cookie.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,32 @@
1818
$.cookie = {
1919
get: function(name) {
2020
var cookieName = encodeURIComponent(name) + '=', cookieStart = document.cookie.indexOf(cookieName), cookieValue = null, cookieEnd, subCookies, i, parts, result = {};
21+
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;
22+
23+
function getData(data) {
24+
if (data === 'true') {
25+
return true;
26+
}
27+
28+
if (data === 'false') {
29+
return false;
30+
}
31+
32+
if (data === 'null') {
33+
return null;
34+
}
35+
36+
// Only convert to a number if it doesn't change the string
37+
if (data === +data + '') {
38+
return +data;
39+
}
40+
41+
if (rbrace.test(data)) {
42+
return JSON.parse(data);
43+
}
44+
45+
return data;
46+
}
2147

2248
if (cookieStart > -1) {
2349
cookieEnd = document.cookie.indexOf(';', cookieStart);
@@ -33,7 +59,7 @@
3359
subCookies = cookieValue.split('&');
3460
for (i = 0, len = subCookies.length; i < len; i++) {
3561
parts = subCookies[i].split('=');
36-
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
62+
result[decodeURIComponent(parts[0])] = getData(decodeURIComponent(parts[1]));
3763
}
3864

3965
return result;

dist/jquery.cookie.min.js

Lines changed: 3 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/jquery.cookie.js

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,32 @@
1818
$.cookie = {
1919
get: function(name) {
2020
var cookieName = encodeURIComponent(name) + '=', cookieStart = document.cookie.indexOf(cookieName), cookieValue = null, cookieEnd, subCookies, i, parts, result = {};
21+
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/;
22+
23+
function getData(data) {
24+
if (data === 'true') {
25+
return true;
26+
}
27+
28+
if (data === 'false') {
29+
return false;
30+
}
31+
32+
if (data === 'null') {
33+
return null;
34+
}
35+
36+
// Only convert to a number if it doesn't change the string
37+
if (data === +data + '') {
38+
return +data;
39+
}
40+
41+
if (rbrace.test(data)) {
42+
return JSON.parse(data);
43+
}
44+
45+
return data;
46+
}
2147

2248
if (cookieStart > -1) {
2349
cookieEnd = document.cookie.indexOf(';', cookieStart);
@@ -33,7 +59,7 @@
3359
subCookies = cookieValue.split('&');
3460
for (i = 0, len = subCookies.length; i < len; i++) {
3561
parts = subCookies[i].split('=');
36-
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
62+
result[decodeURIComponent(parts[0])] = getData(decodeURIComponent(parts[1]));
3763
}
3864

3965
return result;

0 commit comments

Comments
 (0)