Skip to content

Instantly share code, notes, and snippets.

@aceat64
Created June 12, 2025 22:41
Show Gist options
  • Save aceat64/e0ec9ad73ce3dd68ac244ca28eb33b35 to your computer and use it in GitHub Desktop.
Save aceat64/e0ec9ad73ce3dd68ac244ca28eb33b35 to your computer and use it in GitHub Desktop.
Converts a string to a URL-friendly slug (TypeScript)
/**
* Converts a string to a URL-friendly slug by normalizing Unicode characters,
* filtering to allowed characters, and cleaning up the result.
*
* @param input - The input string to slugify (supports UTF-8)
* @param allowedChars - Regex character class of allowed characters (default: letters, digits, underscore)
* @returns A normalized, lowercase slug with no leading/trailing underscores
*
* @example
* slugify("[email protected]") // "saint_14_vanguard_tower"
* slugify("Café & Restaurant") // "cafe_restaurant"
* slugify("Product #123", "a-zA-Z0-9\\-") // "product-123"
*/
function slugify(input: string, allowedChars: string = "a-zA-Z0-9_"): string {
// Create regex to match characters NOT in the allowed set
const regex = new RegExp(`[^${allowedChars}]`, "g");
return (
input
// Normalize Unicode to decomposed form (separates base chars from diacritics)
.normalize("NFKD")
// Replace disallowed characters with underscores
.replace(regex, "_")
// Convert to lowercase
.toLowerCase()
// Collapse multiple consecutive underscores into single underscore
.replace(/_{2,}/g, "_")
// Remove leading and trailing underscores
.replace(/^_+|_+$/g, "")
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment