Adrià Vilanova Martínez | e99c92a | 2023-04-04 02:55:34 +0200 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | func truncateStringWithEllipsis(s string, maxChars int) string { |
| 4 | if len(s) <= maxChars { |
| 5 | return s |
| 6 | } |
| 7 | |
| 8 | // Find the last space within the maximum character limit |
| 9 | i := maxChars - 1 |
| 10 | for ; i >= 0; i-- { |
| 11 | if s[i] == ' ' { |
| 12 | break |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | // If no space found, truncate to the maximum length minus the ellipsis length |
| 17 | if i < 0 { |
| 18 | return s[:maxChars-1] + "…" |
| 19 | } |
| 20 | |
| 21 | // Truncate at the last space found |
| 22 | return s[:i] + "…" |
| 23 | } |