Turn a product title into a URL slug
The catalogue builds a URL from each product title, and the result has to be safe to put in a path.
- Lowercase, and keep only letters a-z and digits.
- Every run of anything else collapses to a single dash.
- No dash at the start or the end.
- A title with nothing usable in it gives an empty string.
slugify(title: string) → string
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
String slugify(String title) {
}
Worked examples
| Call | Result |
|---|---|
slugify(" Blue Widget, 12mm! ") | "blue-widget-12mm" |
slugify("A---B") | "a-b" |
slugify("Already-slugged") | "already-slugged" |
slugify("!!!") | "" |
Hint
Append a dash only when there is already something to separate, then trim the one you may have left on the end.
Reference solution in Java
String slugify(String title) {
StringBuilder sb = new StringBuilder();
for (char ch : title.toLowerCase().toCharArray()) {
if ((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) sb.append(ch);
else if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '-') sb.append('-');
}
if (sb.length() > 0 && sb.charAt(sb.length() - 1) == '-') sb.setLength(sb.length() - 1);
return sb.toString();
}