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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Precompiling patterns as constants avoids recompiling regexes on every call.
- 2Unicode NFD decomposition lets you strip diacritics by removing combining marks.
- 3Order matters when chaining string transforms — each step assumes the previous one's output shape.
Related explainers
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
java
package com.acme.billing.config; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties;
Feature-flagged beans with Spring @ConditionalOnProperty
feature-flags
conditional-beans
strategy-pattern
Intermediate
5 steps
java
public static Map<String, String> parseCookieHeader(String header) { Map<String, String> cookies = new LinkedHashMap<>(); if (header == null || header.isBlank()) { return cookies;
Parsing an HTTP Cookie header in Java
string-parsing
http
url-decoding
Intermediate
6 steps
java
public class TimedSocketReader { private static final int READ_TIMEOUT_MS = 5_000; private static final int CONNECT_TIMEOUT_MS = 3_000;
Reading a socket with connect and read timeouts
sockets
timeouts
io
Intermediate
8 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-url-slugifier-in-java-explained-java-df30/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.