truncateWithEllipsisPreserveWords method

  1. @useResult
String truncateWithEllipsisPreserveWords(
  1. int? cutoff
)

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'

Audited: 2026-06-12 11:26 EDT

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';
  }

  // lastIndexOf returns a code-unit offset, so cut with code-unit substring;
  // the grapheme-indexed substringSafe used before kept text past the space
  // whenever an emoji or combining mark came earlier in the window.
  final String trimmed = searchWindow.substring(0, lastSpaceIndex).trimRight();

  return '$trimmed$ellipsis';
}