Skip to content

Commit 7e580ca

Browse files
committed
feat: accept pairs with missing values
1 parent 221b1d2 commit 7e580ca

3 files changed

Lines changed: 18 additions & 8 deletions

File tree

README.md

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@ npm i --save fast-querystring
1616
- Supports repeating keys in query string
1717
- `foo=bar&foo=baz` parses into `{foo: ['bar', 'baz']}`
1818

19-
### Differences
20-
- Key & value with length 0 is omitted by default
21-
- `foo=bar&hey` parses into `{foo: 'bar'}`, but `node:querystring` returns `{foo: 'bar', hey: ''}`
22-
2319
### Usage
2420

2521
```javascript

lib/parse.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,19 @@ function parse(input) {
2525

2626
// Handle '&' and end of line to pass the current values to result
2727
if (c === 38 || isNaN(c)) {
28-
// Disallow empty key values.
29-
if (equalityIndex - separatorIndex > 0 && i - equalityIndex + 1 > 0) {
30-
key = input.slice(separatorIndex, equalityIndex);
31-
value = input.slice(equalityIndex + 1, i);
28+
const hasOnlyKey = equalityIndex <= separatorIndex;
29+
const keySize =
30+
hasOnlyKey ? i - separatorIndex : equalityIndex - separatorIndex;
31+
32+
if (keySize > 0) {
33+
// Accept empty values, if key size is positive
34+
if (hasOnlyKey) {
35+
key = input.slice(separatorIndex, i);
36+
value = "";
37+
} else {
38+
key = input.slice(separatorIndex, equalityIndex);
39+
value = input.slice(equalityIndex + 1, i);
40+
}
3241

3342
// Optimization: Replace '+' with space
3443
if (hasPlus) {

test/basics.test.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,3 +45,8 @@ test("handles + character", () => {
4545
author: "Yagiz Nizipli",
4646
});
4747
});
48+
49+
test("should accept pairs with missing values", () => {
50+
assert.deepEqual(qs.parse("foo=bar&hey"), { foo: "bar", hey: "" });
51+
assert.deepEqual(qs.parse("hey"), { hey: "" });
52+
});

0 commit comments

Comments
 (0)