Home > Enterprise >  Params without value in URLSearchParams?
Params without value in URLSearchParams?

Time:04-28

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?

CodePudding user response:

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:

Set encoding to the result of getting an output encoding from encoding.
Let output be the empty string.
For each tuple of tuples:
  Let name be the result of running percent-encode after encoding with encoding, tuple’s name, the application/x-www-form-urlencoded percent-encode set, and true.
  Let value be the result of running percent-encode after encoding with encoding, tuple’s value, the application/x-www-form-urlencoded percent-encode set, and true.
  If output is not the empty string, then append U 0026 (&) to output.
  Append name, followed by U 003D (=), followed by value, to output.
Return output.

Due to that final line in the loop, a = is always appended regardless of value.

CodePudding user response:

You can call toString and use a regex to remove the = after parameters with no value.

const params = new URLSearchParams([['a', 1], ['b', 2], ['foo', ''], ['bar', '']])
                .toString().replace(/=(?=&|$)/gm, '');

console.log(params)

  • Related