java 37 lines · 8 steps

Building a URL slugifier in Java

Turn arbitrary titles into clean, hyphenated URL slugs by normalizing Unicode and scrubbing with precompiled regexes.

Explained by highlit
1public final class Slugifier {
2 
3 private static final Pattern NON_LATIN = Pattern.compile("[^\\w-]");
4 private static final Pattern WHITESPACE = Pattern.compile("[\\s]+");
5 private static final Pattern EDGE_DASHES = Pattern.compile("(^-+)|(-+$)");
6 private static final Pattern MULTI_DASH = Pattern.compile("-{2,}");
7 
8 private Slugifier() {
9 }
10 
11 public static String slugify(String title) {
12 if (title == null || title.isBlank()) {
13 return "";
14 }
15 
16 String normalized = Normalizer.normalize(title, Normalizer.Form.NFD)
17 .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
18 
19 String slug = WHITESPACE.matcher(normalized.trim()).replaceAll("-");
20 slug = slug.toLowerCase(Locale.ENGLISH);
21 slug = NON_LATIN.matcher(slug).replaceAll("");
22 slug = MULTI_DASH.matcher(slug).replaceAll("-");
23 slug = EDGE_DASHES.matcher(slug).replaceAll("");
24 
25 return slug;
26 }
27 
28 public static String slugify(String title, int maxLength) {
29 String slug = slugify(title);
30 if (slug.length() <= maxLength) {
31 return slug;
32 }
33 String truncated = slug.substring(0, maxLength);
34 int lastDash = truncated.lastIndexOf('-');
35 return lastDash > 0 ? truncated.substring(0, lastDash) : truncated;
36 }
37}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Precompiling patterns as constants avoids recompiling regexes on every call.
  2. 2Unicode NFD decomposition lets you strip diacritics by removing combining marks.
  3. 3Order matters when chaining string transforms — each step assumes the previous one's output shape.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a URL slugifier in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code