Construir URL query strings from objects
Construct properly encoded consulta cadenas de JavaScript objetos. Handle arreglos, nested objetos, y special caracteres correctly.
- 1
Building a query string requires: key=value pairs joined by &, percent-encoding of keys and values, handling of arrays (repeated keys or bracket notation), and omitting undefined/null values. The order of parameters may matter for caching and signature verification.
- 2 Codificador de URL →
Percent-encode each key and value. Spaces → %20, & → %26, = → %3D, non-ASCII → UTF-8 percent-encoding. Use encodeURIComponent (not encodeURI) for query string values — it encodes all reserved characters.
- 3 Analizador de URL →
Verify the built URL by parsing it back. The parsed query string should match the original object. This round-trip test catches encoding errors and structural issues.
- 4 url-encode → hex-encode
Use the URL encode workflow to encode a payload object as a query string, with proper handling of nested parameters and special characters.
Preguntas frecuentes
- Should I use encodeURIComponent or encodeURI?
- Use encodeURIComponent for query string keys and values — it encodes all reserved characters (&, =, +, /, etc.). Use encodeURI for full URLs — it preserves URL structure characters (?, &, =, /). Using the wrong one causes encoding bugs.
- How do I handle undefined and null?
- Omit undefined and null values — they should not appear in the query string. For falsey values: 0, false, and empty string should be included as key=0, key=false, key=. Decide based on your API contract — some APIs distinguish absent vs. empty.