trimWithEllipsis method

  1. @useResult
String trimWithEllipsis({
  1. int minLength = 5,
})

Returns a truncated version of this string with ellipsis, keeping the first and last minLength characters.

All counts are grapheme clusters (user-perceived characters), so emoji and letters with combining marks count as one and are never split. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String trimWithEllipsis({int minLength = 5}) {
  // Grapheme count, not code-unit `length`: the slices below are
  // grapheme-indexed (substringSafe), so a code-unit length picked the wrong
  // branch and the wrong tail start whenever the string held emoji.
  final int graphemeCount = characters.length;
  if (graphemeCount < minLength) {
    return StringExtensions.ellipsis;
  }

  if (graphemeCount < (minLength * 2) + 2) {
    return substringSafe(0, minLength) + StringExtensions.ellipsis;
  }

  return substringSafe(0, minLength) +
      StringExtensions.ellipsis +
      substringSafe(graphemeCount - minLength);
}