Skip to content

Commit eb74178

Browse files
committed
feat: handle edge cases for stability
1 parent e691252 commit eb74178

2 files changed

Lines changed: 27 additions & 3 deletions

File tree

lib/parse.js

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,8 @@ function parse(input) {
2222
for (let i = 0; i < input.length + 1; i++) {
2323
let c = input.charCodeAt(i);
2424

25-
// Handle '&' and end of line to pass the current values to result
26-
if (c === 38 || isNaN(c)) {
25+
// Handle '&', '#' and end of line to pass the current values to result
26+
if (c === 38 || c === 35 || isNaN(c)) {
2727
// Disallow empty key values.
2828
if (equalityIndex - separatorIndex > 0 && i - equalityIndex + 1 > 0) {
2929
key = input.slice(separatorIndex, equalityIndex);
@@ -48,17 +48,28 @@ function parse(input) {
4848
}
4949
}
5050

51+
// Terminate loop when parser encounters '#'
52+
if (c === 35) {
53+
break;
54+
}
55+
5156
// Reset reading key value pairs
5257
separatorIndex = i + 1;
5358
equalityIndex = i + 1;
59+
shouldEncode = false;
5460
}
55-
// Handle equal operator
61+
// Check '='
5662
else if (c === 61) {
5763
equalityIndex = i;
5864
}
5965
// Check '+', and replace it with empty space.
6066
else if (c === 43) {
6167
input[i] = " ";
68+
}
69+
// Check '?' in the beginning, and omit if exists
70+
else if (c === 63 && i === 0) {
71+
separatorIndex = 1;
72+
equalityIndex = 1;
6273
} else {
6374
// Check '%' character for encoding
6475
if (c === 37) {

test/basics.test.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,16 @@ test("should parse the basics", () => {
2929
test("should throw error on invalid type", () => {
3030
assert.throws(() => qs.parse(5), "Invalid Input");
3131
});
32+
33+
test("handles & on first/last character", () => {
34+
assert.deepEqual(qs.parse("&hello=world"), { hello: "world" });
35+
assert.deepEqual(qs.parse("hello=world&"), { hello: "world" });
36+
});
37+
38+
test("handles ? on first character", () => {
39+
assert.deepEqual(qs.parse("?hello=world"), { hello: "world" });
40+
});
41+
42+
test("removes fragment from string", () => {
43+
assert.deepEqual(qs.parse("foo=bar#hello"), { foo: "bar" });
44+
});

0 commit comments

Comments
 (0)