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
java
public class SlidingLogRateLimiter { private final int maxRequests; private final long windowMillis;
How a sliding-log rate limiter works
rate-limiting
concurrency
sliding-window
Advanced
8 steps
java
@Repository public interface OrderRepository extends JpaRepository<Order, Long> { @Query("""
Keyset pagination with Spring Data JPA
pagination
cursor
jpa
Advanced
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
java
public record FixedWidthField(String name, int start, int end) { public String extract(String line) { int from = Math.min(start, line.length());
Parsing fixed-width text in Java
records
parsing
streams
Intermediate
7 steps
java
@RestController @RequestMapping("/api/quotes") public class QuoteStreamController {
Streaming market quotes with Spring WebFlux
reactive-streams
backpressure
server-sent-events
Advanced
9 steps
java
@Controller public class BookController { private final BookService bookService;
Solving GraphQL N+1 with batch mapping in Spring
graphql
n+1-problem
batching
Intermediate
8 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.