@nestbolt/sluggable
Transliteration
Built-in transliteration for non-Latin characters and how to provide a custom transliterator.
@nestbolt/sluggable includes a built-in transliteration engine that converts non-Latin characters to their ASCII equivalents before generating the slug. This ensures URL-safe slugs regardless of the source language.
Supported Character Sets
The built-in transliterator handles:
| Script | Examples | Output |
|---|---|---|
| Accented Latin | café résumé | cafe resume |
| German | Ärger Öffnung Über Straße | Aerger Oeffnung Ueber Strasse |
| Eastern European | Łódź cześć | Lodz czesc |
| Turkish | İstanbul güneş | Istanbul gunes |
| Nordic | Ðóttir | Dottir |
| Arabic | مرحبا | mrhba |
| Cyrillic | Москва | Moskva |
Examples
import { SluggableService } from "@nestbolt/sluggable";
sluggable.generateSlug("café résumé"); // "cafe-resume"
sluggable.generateSlug("Ärger im Büro"); // "aerger-im-buero"
sluggable.generateSlug("Łódź cześć"); // "lodz-czesc"Disabling Transliteration
Disable transliteration globally:
SluggableModule.forRoot({ transliterate: false })Or per-call:
sluggable.generateSlug("café", { transliterate: false });
// "caf" — non-ASCII characters are stripped by the slugifierWhen transliteration is disabled, non-ASCII characters are removed during slugification since they don't match [a-zA-Z0-9].
Custom Transliterator
Provide your own transliteration function to handle special cases or use a different library:
SluggableModule.forRoot({
transliterator: (input: string) => {
// Your custom transliteration logic
return input
.replace(/ö/g, "o")
.replace(/ü/g, "u")
.replace(/ä/g, "a");
},
})The custom transliterator receives the raw input string and should return a string with non-Latin characters replaced by ASCII equivalents. The result is then passed through the slugifier.
Using a Third-Party Library
You can use any transliteration library:
import transliterateLib from "transliteration";
SluggableModule.forRoot({
transliterator: (input) => transliterateLib.transliterate(input),
})Using the Transliterate Utility Directly
The built-in transliterate function is exported for standalone use:
import { transliterate } from "@nestbolt/sluggable";
transliterate("café résumé"); // "cafe resume"
transliterate("Москва"); // "Moskva"
transliterate("مرحبا"); // "mrhba"Using the Slugify Utility Directly
The slugify function is also exported for use outside the subscriber:
import { slugify } from "@nestbolt/sluggable";
slugify("Hello World"); // "hello-world"
slugify("Hello World", { separator: "_" }); // "hello_world"
slugify("Hello World", { maxLength: 5 }); // "hello"
slugify("Hello World", { lowercase: false }); // "Hello-World"Note that slugify does not transliterate -- it assumes input is already ASCII. Use transliterate() first if needed, or use SluggableService.generateSlug() which chains both.