UrlHelper - sebamar88/bytekit GitHub Wiki
🔗 UrlHelper
EN: Static utilities for URL query string serialization and SEO-friendly slug generation. Supports arrays, nested objects, and multiple array formats.
ES: Utilidades estáticas para serialización de query strings de URL y generación de slugs amigables para SEO. Soporta arrays, objetos anidados y múltiples formatos de array.
¿Por qué UrlHelper? / Why UrlHelper?
ES: Construir query strings con arrays, objetos anidados, y valores especiales (null, booleanos, fechas) es sorprendentemente complejo. URLSearchParams nativo no soporta arrays ni objetos anidados. UrlHelper.stringify() maneja todo eso con opciones configurables. Además, slugify() convierte cualquier texto o conjunto de parámetros en un slug limpio, sin acentos, y listo para URLs y SEO.
EN: Building query strings with arrays, nested objects, and special values (null, booleans, dates) is surprisingly complex. Native URLSearchParams doesn't support arrays or nested objects. UrlHelper.stringify() handles all of that with configurable options. Additionally, slugify() converts any text or set of parameters into a clean, accent-free slug ready for URLs and SEO.
📦 Import
import { UrlHelper } from "bytekit";
📋 Static Methods / Métodos Estáticos
| Method / Método | Signature / Firma | Description (EN) | Descripción (ES) |
|---|---|---|---|
stringify |
stringify(params: Record<string, unknown> | null | undefined, options?: QueryStringOptions): string |
Serialize an object to a URL query string | Serializa un objeto a un query string de URL |
slugify |
slugify(params: Record<string, unknown> | string | null | undefined, options?: string | SlugifyOptions): string |
Convert text or object to a URL-safe SEO-friendly slug | Convierte texto u objeto a un slug URL-safe amigable para SEO |
🧩 Types / Tipos
QueryStringOptions
| Property / Propiedad | Type / Tipo | Default | Description (EN) | Descripción (ES) |
|---|---|---|---|---|
arrayFormat |
"repeat" | "bracket" | "comma" |
"repeat" |
How arrays are serialized in the query string | Cómo se serializan arrays en el query string |
skipNull |
boolean |
true |
Skip keys with null values |
Omite claves con valores null |
skipEmptyString |
boolean |
false |
Skip keys with empty string values | Omite claves con valores de cadena vacía |
encode |
boolean |
true |
Apply encodeURIComponent to keys and values |
Aplica encodeURIComponent a claves y valores |
sortKeys |
boolean |
true |
Sort keys alphabetically | Ordena claves alfabéticamente |
Array Format Examples / Ejemplos de Formato de Array
params = { colors: ["red", "blue"] }
"repeat" → colors=red&colors=blue
"bracket" → colors[]=red&colors[]=blue
"comma" → colors=red,blue
SlugifyOptions
| Property / Propiedad | Type / Tipo | Default | Description (EN) | Descripción (ES) |
|---|---|---|---|---|
separator |
string |
"-" |
Character used between words | Carácter usado entre palabras |
lowercase |
boolean |
true |
Convert to lowercase | Convierte a minúsculas |
🧠 How It Works / Cómo Funciona
EN:
stringify()walks the object recursively, flattening nested objects with bracket notation (key[child]), handling arrays according toarrayFormat, serializing Dates as ISO strings and booleans as"true"/"false". Keys are sorted alphabetically by default.slugify()normalizes Unicode (NFD), strips diacritics, lowercases, and replaces non-alphanumeric runs with the separator.ES:
stringify()recorre el objeto recursivamente, aplanando objetos anidados con notación de brackets (key[child]), manejando arrays segúnarrayFormat, serializando Dates como cadenas ISO y booleanos como"true"/"false". Las claves se ordenan alfabéticamente por defecto.slugify()normaliza Unicode (NFD), elimina diacríticos, convierte a minúsculas y reemplaza secuencias no alfanuméricas con el separador.
stringify({ a: 1, filters: { min: 10 }, tags: ["x","y"] })
│
┌────▼──────────────────┐
│ Flatten nested objects │ filters.min → filters[min]=10
│ Expand arrays │ tags → tags=x&tags=y
│ Serialize values │ a → a=1
│ Encode & sort │
└────┬──────────────────┘
│
"a=1&filters%5Bmin%5D=10&tags=x&tags=y"
slugify("Pantalón Jean Negro")
│
┌────▼──────────────┐
│ NFD normalize │ "Pantalón" → "Pantalon"
│ Remove diacritics │
│ Lowercase │ "Pantalon Jean Negro" → "pantalon jean negro"
│ Replace non-alnum │ → "pantalon-jean-negro"
└────┬──────────────┘
│
"pantalon-jean-negro"
💡 Examples / Ejemplos
Basic Query String / Query String Básico
import { UrlHelper } from "bytekit";
const qs = UrlHelper.stringify({
page: 1,
limit: 20,
search: "bytekit utils",
});
console.log(qs);
// "limit=20&page=1&search=bytekit%20utils"
// (keys sorted alphabetically, values encoded)
Arrays / Arrays
// EN: "repeat" format (default) — same key repeated
// ES: Formato "repeat" (default) — misma clave repetida
UrlHelper.stringify({ colors: ["red", "blue", "green"] });
// "colors=red&colors=blue&colors=green"
// EN: "bracket" format — key[] syntax
// ES: Formato "bracket" — sintaxis key[]
UrlHelper.stringify(
{ colors: ["red", "blue"] },
{ arrayFormat: "bracket" }
);
// "colors%5B%5D=red&colors%5B%5D=blue"
// EN: "comma" format — comma-separated
// ES: Formato "comma" — separado por comas
UrlHelper.stringify(
{ colors: ["red", "blue"] },
{ arrayFormat: "comma" }
);
// "colors=red%2Cblue"
Nested Objects / Objetos Anidados
UrlHelper.stringify({
user: "ana",
filters: {
minPrice: 100,
maxPrice: 500,
categories: ["electronics", "books"],
},
});
// "filters%5Bcategories%5D=electronics&filters%5Bcategories%5D=books&filters%5BmaxPrice%5D=500&filters%5BminPrice%5D=100&user=ana"
// Decoded: filters[categories]=electronics&filters[categories]=books&filters[maxPrice]=500&filters[minPrice]=100&user=ana
Special Values / Valores Especiales
// EN: Booleans, Dates, null, undefined
// ES: Booleanos, Dates, null, undefined
UrlHelper.stringify({
active: true,
archived: false,
since: new Date("2025-01-01"),
deleted: null, // Skipped (skipNull: true by default)
pending: undefined, // Always skipped
});
// "active=true&archived=false&since=2025-01-01T00%3A00%3A00.000Z"
Options: skipNull, skipEmptyString, encode
// EN: Include null values as empty strings
// ES: Incluye valores null como cadenas vacías
UrlHelper.stringify(
{ a: 1, b: null, c: "" },
{ skipNull: false, skipEmptyString: true }
);
// "a=1&b=" (c skipped because empty string)
// EN: Disable encoding for human-readable output
// ES: Desactiva codificación para salida legible
UrlHelper.stringify(
{ q: "hello world", tags: ["a", "b"] },
{ encode: false }
);
// "q=hello world&tags=a&tags=b"
slugify — Text to Slug / Texto a Slug
// EN: From a plain string
// ES: Desde una cadena de texto
UrlHelper.slugify("Pantalón Jean Negro");
// "pantalon-jean-negro"
UrlHelper.slugify("Café con Leche — Edición Especial!");
// "cafe-con-leche-edicion-especial"
UrlHelper.slugify(" Multiple spaces here ");
// "multiple-spaces-here"
slugify — Object to Slug / Objeto a Slug
// EN: From an object — keys and values are concatenated
// ES: Desde un objeto — claves y valores se concatenan
UrlHelper.slugify({ category: "Smart Phones", brand: "Apple" });
// "brand-apple-category-smart-phones"
// (keys sorted alphabetically by default)
slugify — Custom Separator / Separador Personalizado
// EN: Use underscore separator
// ES: Usa separador de guión bajo
UrlHelper.slugify("Hello World", { separator: "_" });
// "hello_world"
// EN: Preserve case
// ES: Preservar mayúsculas/minúsculas
UrlHelper.slugify("Hello World", { separator: "-", lowercase: false });
// "Hello-World"
// EN: Legacy: pass separator as string directly
// ES: Legacy: pasa separador como string directamente
UrlHelper.slugify("Hello World", "_");
// "hello_world"
Building Full URLs / Construyendo URLs Completas
// EN: Combine with native URL API
// ES: Combina con la API nativa de URL
const base = "https://api.example.com/v2/products";
const query = UrlHelper.stringify({
page: 2,
limit: 10,
sort: "price",
filters: { minPrice: 50, category: "electronics" },
});
const fullUrl = `${base}?${query}`;
console.log(fullUrl);
// "https://api.example.com/v2/products?filters%5Bcategory%5D=electronics&filters%5BminPrice%5D=50&limit=10&page=2&sort=price"
E-Commerce Slug Example / Ejemplo de Slug para E-Commerce
// EN: Generate a product URL slug
// ES: Genera un slug de URL para producto
const product = { name: "Camiseta Algodón Orgánico", color: "Azul Marino" };
const slug = UrlHelper.slugify(`${product.name} ${product.color}`);
const productUrl = `https://tienda.example.com/productos/${slug}`;
console.log(productUrl);
// "https://tienda.example.com/productos/camiseta-algodon-organico-azul-marino"
🔗 Véase También / See Also
- ApiClient — Uses query string serialization internally for
searchParams/ Usa serialización de query string internamente parasearchParams - CryptoUtils — Encoding and hashing utilities / Utilidades de codificación y hashing
- CompressionUtils — Base64 encoding for URL-safe data / Codificación Base64 para datos URL-safe