truncateWithEllipsisPreserveWords method
Returns the string truncated to cutoff graphemes with an ellipsis,
preserving whole words.
Truncates at the last full word that fits within cutoff. If the first
word is longer than the cutoff, falls back to simple truncation.
Example:
'Hello World'.truncateWithEllipsisPreserveWords(8); // 'Hello…'
'Hello World'.truncateWithEllipsisPreserveWords(20); // 'Hello World'
Implementation
@useResult
String truncateWithEllipsisPreserveWords(int? cutoff) {
final int charLength = characters.length;
if (isEmpty || cutoff == null || cutoff <= 0 || charLength <= cutoff) {
return this;
}
final int searchLength = cutoff + 1 > charLength ? charLength : cutoff + 1;
final String searchWindow = characters.take(searchLength).toString();
final int lastSpaceIndex = searchWindow.lastIndexOf(' ');
if (lastSpaceIndex == -1 || lastSpaceIndex == 0) {
return '${characters.take(cutoff).toString()}$ellipsis';
}
final String trimmed = searchWindow.substringSafe(0, lastSpaceIndex).trimRight();
return '$trimmed$ellipsis';
}