Skip to content

Commit 885bb06

Browse files
authored
fix(query): prevent trailing & in query (vuejs#935)
* fix(query): `&` sign doesn't remove properly * test: improve title and remove unnecessary test case
1 parent 477d673 commit 885bb06

File tree

2 files changed

+11
-5
lines changed

2 files changed

+11
-5
lines changed

__tests__/stringifyQuery.spec.ts

+6
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ describe('stringifyQuery', () => {
2828
expect(stringifyQuery({ e: undefined, b: 'a' })).toEqual('b=a')
2929
})
3030

31+
it('ignores undefined and empty arrays', () => {
32+
expect(
33+
stringifyQuery({ a: [undefined, 'b'], b: undefined, c: [] })
34+
).toEqual('a=b')
35+
})
36+
3137
it('stringifies arrays', () => {
3238
expect(stringifyQuery({ e: ['b', 'a'] })).toEqual('e=b&e=a')
3339
})

src/query.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -89,12 +89,11 @@ export function parseQuery(search: string): LocationQuery {
8989
export function stringifyQuery(query: LocationQueryRaw): string {
9090
let search = ''
9191
for (let key in query) {
92-
if (search.length) search += '&'
9392
const value = query[key]
9493
key = encodeQueryKey(key)
9594
if (value == null) {
9695
// only null adds the value
97-
if (value !== undefined) search += key
96+
if (value !== undefined) search += (search.length ? '&' : '') + key
9897
continue
9998
}
10099
// keep null values
@@ -103,9 +102,10 @@ export function stringifyQuery(query: LocationQueryRaw): string {
103102
: [value && encodeQueryValue(value)]
104103

105104
for (let i = 0; i < values.length; i++) {
106-
// only append & with i > 0
107-
search += (i ? '&' : '') + key
108-
if (values[i] != null) search += ('=' + values[i]) as string
105+
if (values[i] === undefined) continue
106+
// only append & with non-empty search
107+
search += (search.length ? '&' : '') + key
108+
if (values[i] !== null) search += ('=' + values[i]) as string
109109
}
110110
}
111111

0 commit comments

Comments
 (0)