diff --git a/lib/stringify.js b/lib/stringify.js index a2dea7e..c59dba1 100644 --- a/lib/stringify.js +++ b/lib/stringify.js @@ -39,12 +39,14 @@ function stringify(input) { const value = input[key]; const encodedKey = encodeString(key) + "="; - if (i) { - result += separator; - } - if (Array.isArray(value)) { valueLength = value.length; + if (valueLength === 0) { + continue; + } + if (result.length > 0) { + result += separator; + } for (let j = 0; j < valueLength; j++) { if (j) { result += separator; @@ -56,6 +58,9 @@ function stringify(input) { result += getAsPrimitive(value[j]); } } else { + if (result.length > 0) { + result += separator; + } result += encodedKey; result += getAsPrimitive(value); } diff --git a/test/stringify.test.ts b/test/stringify.test.ts index dd3980a..6a671ea 100644 --- a/test/stringify.test.ts +++ b/test/stringify.test.ts @@ -97,6 +97,13 @@ test("should coerce numbers to string", () => { assert.strictEqual(qs.stringify({ foo: Number.POSITIVE_INFINITY }), "foo="); }); +test("should skip empty array values without leaving stray separators", () => { + assert.strictEqual(qs.stringify({ a: [], b: "1" }), "b=1"); + assert.strictEqual(qs.stringify({ a: "1", b: [] }), "a=1"); + assert.strictEqual(qs.stringify({ a: "1", b: [], c: "2" }), "a=1&c=2"); + assert.strictEqual(qs.stringify({ a: [] }), ""); +}); + test("should return empty string on certain inputs", () => { assert.strictEqual(qs.stringify(undefined as never), ""); assert.strictEqual(qs.stringify(0 as never), "");