I'd like to get an a=1&b=2&foo
URL with URLSearchParams
.
Here's what I tried:
new URLSearchParams([['a', 1], ['b', 2], ['foo']]).toString();
// Uncaught TypeError: Failed to construct 'URLSearchParams':
// Failed to construct 'URLSearchParams': Sequence initializer must only contain pair elements
new URLSearchParams([['a', 1], ['b', 2], ['foo', '']]).toString();
// a=1&b=2&foo=
new URLSearchParams([['a', 1], ['b', 2], ['foo', null]]).toString();
// a=1&b=2&foo=null
new URLSearchParams([['a', 1], ['b', 2], ['foo', undefined]]).toString();
// a=1&b=2&foo=undefined
Can it be done?
It doesn't look possible. The URL standard says that the query object that a URLSearchParams has internally is a list of name-value pairs, and that when stringified, it runs the application/x-www-form-urlencoded serializer, which does:
Due to that final line in the loop, a
=
is always appended regardless of value.