Skip to content

Commit b8b1771

Browse files
committed
Added type coercion.
1 parent 215a960 commit b8b1771

File tree

2 files changed

+18
-2
lines changed

2 files changed

+18
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
This plugin attempts to make working with querystrings easier. The primary function exposed is `$.querystring`, which handles both parsing & serialization (depending on the type of argument passed in). A `$.fn.querystring` method is also provided, which makes getting & setting the querystring of `<a>` elements more convenient.
22

3-
_Currently only the simplest cases work, but the goal is to support nested objects, arrays, and type coercion. Please refer to the test suite for more info._
3+
_Currently only the simplest cases work, but the goal is to support nested objects and arrays. Please refer to the test suite for more info._
44

55
Basic usage
66
-----------

jquery.querystring.js

+17-1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,21 @@
99
}
1010
};
1111

12+
// Returns the JavaScript value of a querystring parameter.
13+
// Decodes the string & coerces it to the appropriate JavaScript type.
14+
// Examples:
15+
// 'Coffee%20and%20milk' => 'Coffee and milk'
16+
// 'true' => true
17+
// '21' => 21
18+
function parseValue(value) {
19+
value = decodeURIComponent(value);
20+
try {
21+
return JSON.parse(value);
22+
} catch(e) {
23+
return value;
24+
}
25+
}
26+
1227
// Takes a URL (or fragment) and parses the querystring portion into an object.
1328
// Returns an empty object if there is no querystring.
1429
function parse(url) {
@@ -20,7 +35,8 @@
2035
}
2136

2237
$.each(query.split('&'), function(idx, pair) {
23-
params[pair.split('=')[0]] = decodeURIComponent(pair.split('=')[1] || '');
38+
pair = pair.split('=');
39+
params[pair[0]] = parseValue(pair[1] || '');
2440
});
2541

2642
return params;

0 commit comments

Comments
 (0)