Slugify converts a free-form name into a URL-safe slug. It lowercases, replaces runs of non-alphanumeric chars with dashes, strips leading/trailing dashes, and truncates to maxSlugWords words. Returns an error if the result is empty.
(name string)
| 18 | // strips leading/trailing dashes, and truncates to maxSlugWords words. |
| 19 | // Returns an error if the result is empty. |
| 20 | func Slugify(name string) (string, error) { |
| 21 | s := strings.ToLower(strings.TrimSpace(name)) |
| 22 | s = slugNonAlnum.ReplaceAllString(s, "-") |
| 23 | s = strings.Trim(s, "-") |
| 24 | if s == "" { |
| 25 | return "", fmt.Errorf("cannot slugify %q: result is empty", name) |
| 26 | } |
| 27 | // Truncate to maxSlugWords dash-separated parts. |
| 28 | parts := strings.SplitN(s, "-", maxSlugWords+1) |
| 29 | if len(parts) > maxSlugWords { |
| 30 | s = strings.Join(parts[:maxSlugWords], "-") |
| 31 | } |
| 32 | return s, nil |
| 33 | } |
no outgoing calls