Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to create a slug from a string

Short answer

A slug is the part of a page address made of Latin letters, digits and hyphens. Lowercase the string and replace everything else with a hyphen:

void main() {
    String title = "Hello, World! Java 25 is here";
 
    String slug = title.toLowerCase(Locale.ROOT)
            .replaceAll("[^a-z0-9]+", "-")
            .replaceAll("^-|-$", "");
    IO.println(slug);
}

Output:

hello-world-java-25-is-here

Accented letters

Normalizer splits é into e and a separate mark that you can then remove:

import java.text.Normalizer;
 
String slugify(String text) {
    String plain = Normalizer.normalize(text, Normalizer.Form.NFD).replaceAll("\\p{M}", "");
    return plain.toLowerCase(Locale.ROOT)
            .replaceAll("[^a-z0-9]+", "-")
            .replaceAll("^-|-$", "");
}
 
void main() {
    IO.println(slugify("Crème Brûlée — à la carte"));
}

Output:

creme-brulee-a-la-carte

The java.text package is also part of java.base, but an explicit import is shown here to make it clear where the class comes from.

Cyrillic

Cyrillic letters do not decompose into Latin ones — you have to transliterate them with a table:

void main() {
    var table = Map.of('п', "p", 'р', "r", 'и', "i", 'в', "v", 'е', "e", 'т', "t");
    var result = new StringBuilder();
    for (char c : "привет".toCharArray()) {
        result.append(table.getOrDefault(c, String.valueOf(c)));
    }
    IO.println(result);
}

Output:

privet

In a real project the table contains all 33 letters.

Common mistake

Forgetting to remove hyphens at the ends. A string that starts or ends with punctuation gives an ugly address:

void main() {
    IO.println("¡Hola!".toLowerCase().replaceAll("[^a-z0-9]+", "-"));
}

Output:

-hola-

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.