File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed
snippets/java/string-manipulation Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 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+ ```
You can’t perform that action at this time.
0 commit comments