Skip to content

Commit 3fd6fd9

Browse files
yadielarsindresorhus
authored andcommitted
Add decode option to .parse() (#124)
1 parent e5a6c1f commit 3fd6fd9

3 files changed

Lines changed: 21 additions & 4 deletions

File tree

index.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,14 @@ function encode(value, options) {
9696
return value;
9797
}
9898

99+
function decode(value, options) {
100+
if (options.decode) {
101+
return decodeComponent(value);
102+
}
103+
104+
return value;
105+
}
106+
99107
function keysSorter(input) {
100108
if (Array.isArray(input)) {
101109
return input.sort();
@@ -119,7 +127,7 @@ function extract(input) {
119127
}
120128

121129
function parse(input, options) {
122-
options = Object.assign({arrayFormat: 'none'}, options);
130+
options = Object.assign({decode: true, arrayFormat: 'none'}, options);
123131

124132
const formatter = parserForArrayFormat(options);
125133

@@ -141,9 +149,9 @@ function parse(input, options) {
141149

142150
// Missing `=` should be `null`:
143151
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
144-
value = value === undefined ? null : decodeComponent(value);
152+
value = value === undefined ? null : decode(value, options);
145153

146-
formatter(decodeComponent(key), value, ret);
154+
formatter(decode(key, options), value, ret);
147155
}
148156

149157
return Object.keys(ret).sort().reduce((result, key) => {

readme.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,12 @@ Parse a query string into an object. Leading `?` or `#` are ignored, so you can
6262

6363
The returned object is created with [`Object.create(null)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) and thus does not have a `prototype`.
6464

65-
URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component).
65+
#### decode
66+
67+
Type: `boolean`<br>
68+
Default: `true`
69+
70+
Decode the keys and values. URI components are decoded with [`decode-uri-component`](https://github.com/SamVerschueren/decode-uri-component).
6671

6772
#### arrayFormat
6873

test/parse.js

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,3 +179,7 @@ test('decode keys and values', t => {
179179
t.deepEqual(m.parse('st%C3%A5le=foo'), {ståle: 'foo'});
180180
t.deepEqual(m.parse('foo=%7B%ab%%7C%de%%7D+%%7Bst%C3%A5le%7D%'), {foo: '{%ab%|%de%} %{ståle}%'});
181181
});
182+
183+
test('disable decoding of keys and values', t => {
184+
t.deepEqual(m.parse('tags=postal%20office,burger%2C%20fries%20and%20coke', {decode: false}), {tags: 'postal%20office,burger%2C%20fries%20and%20coke'});
185+
});

0 commit comments

Comments
 (0)