truncateMiddle method

String truncateMiddle({
  1. int maxChars = 3,
  2. String truncateKey = '...',
})

Truncates a long String in the middle while retaining the beginning and the end.

Example : 'Hello World'.truncateMiddle(3) // 'Hel...rld'

Implementation

String truncateMiddle({int maxChars = 3, String truncateKey = '...'}) {
  if (isEmptyOrNull || maxChars < 1) {
    return this;
  }

  if ((maxChars * 2) >= length) {
    return this;
  }

  return '${firstNChars(n: maxChars)}$truncateKey${lastNChars(n: maxChars)}';
}