Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

102
Visualizações
Params without value in URLSearchParams?

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda