truncateWords method

String truncateWords(
  1. int maxWords, {
  2. String ellipsis = '…',
})

Truncates this string to maxWords words, appending ellipsis if truncation occurs.

'The quick brown fox'.truncateWords(3) // 'The quick brown…'

Implementation

String truncateWords(int maxWords, {String ellipsis = '…'}) {
  if (isEmpty) return '';
  final words = trim().split(RegExp(r'\s+'));
  if (words.length <= maxWords) return this;
  return '${words.take(maxWords).join(' ')}$ellipsis';
}