package main | |
func truncateStringWithEllipsis(s string, maxChars int) string { | |
if len(s) <= maxChars { | |
return s | |
} | |
// Find the last space within the maximum character limit | |
i := maxChars - 1 | |
for ; i >= 0; i-- { | |
if s[i] == ' ' { | |
break | |
} | |
} | |
// If no space found, truncate to the maximum length minus the ellipsis length | |
if i < 0 { | |
return s[:maxChars-1] + "…" | |
} | |
// Truncate at the last space found | |
return s[:i] + "…" | |
} |