Me gustaría obtener una URL a a=1&b=2&foo con URLSearchParams .
Esto es lo que probé:
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=undefinedSe puede hacer?
No parece posible. El estándar de URL dice que el objeto de consulta que un URLSearchParams tiene internamente es una lista de pares de nombre y valor, y que cuando se encadena, ejecuta el serializador application/x-www-form-urlencoded , que hace lo siguiente:
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. Debido a esa línea final en el ciclo, siempre se agrega a = independientemente del valor.
Puede llamar a toString y usar una expresión regular para eliminar los parámetros = after sin valor.
const params = new URLSearchParams([['a', 1], ['b', 2], ['foo', ''], ['bar', '']]) .toString().replace(/=(?=&|$)/gm, ''); console.log(params)