Skip to content

Commit f5b07b5

Browse files
committed
slugify snippet
1 parent 7832e60 commit f5b07b5

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
---
2+
title: Slugify String
3+
description: Converts a string into a URL-friendly slug format
4+
author: Mcbencrafter
5+
tags: string,slug,slugify
6+
---
7+
8+
```java
9+
public static String slugify(String text, String separator) {
10+
if (text == null)
11+
return "";
12+
13+
// used to decompose accented characters to their base characters (e.g. "é" to "e")
14+
String normalizedString = Normalizer.normalize(text, Normalizer.Form.NFD);
15+
normalizedString = normalizedString.replaceAll("[\\p{InCombiningDiacriticalMarks}]", "");
16+
17+
String slug = normalizedString.trim()
18+
.toLowerCase()
19+
.replaceAll("\\s+", separator)
20+
.replaceAll("[^a-z0-9\\-_" + separator + "]", "")
21+
.replaceAll("_", separator)
22+
.replaceAll("-", separator)
23+
.replaceAll(separator + "+", separator)
24+
.replaceAll(separator + "$", "");
25+
26+
return slug;
27+
}
28+
29+
// Usage:
30+
System.out.println(slugify("Hello World-#123-é", "-")); // "hello-world-123-e"
31+
```

0 commit comments

Comments
 (0)