Skip to content

slugify

Edit

Converts text into a lowercase, URL-safe Unicode slug.

slugify.ts
/** Converts text into a lowercase, URL-safe Unicode slug. */
export const slugify = (value: string, separator: string = "-"): string => {
if (!/^[-._~]+$/.test(separator)) {
throw new TypeError(
"separator must contain only URL-safe punctuation characters: -._~"
);
}
const normalized = value
.normalize("NFKD")
.replace(/(?<=\p{Script=Latin})\p{M}+/gu, "")
.toLowerCase();
const words =
normalized.match(/[\p{L}\p{N}][\p{L}\p{N}\p{M}]*/gu) ?? [];
return words.join(separator);
};
Terminal
wget -O src/lib/slugify.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/slugify.ts
slugify.example.ts
import { slugify } from "./slugify";
const slug = slugify("Déjà Vu: A Guide");
// "deja-vu-a-guide"
const unicodeSlug = slugify("नमस्ते संसार", "_");
// "नमस्ते_संसार"
  • value (string) — Text to normalize.
  • separator (string) — One or more URL-safe punctuation characters (-, ., _, or ~), defaulting to -.
  • Latin diacritics are removed while marks attached to letters or numbers in other Unicode scripts are retained.
  • Reserved URL delimiters, whitespace, alphanumeric characters, and other Unicode symbols are rejected as separators.