lastNWords method

  1. @useResult
String lastNWords(
  1. int n
)

Returns the last n words (split on whitespace), preserving their order.

Returns the empty string when n is <= 0, and the whole trimmed string when it has n or fewer words.

Example:

'the quick brown fox'.lastNWords(2); // 'brown fox'

Implementation

@useResult
String lastNWords(int n) {
  if (n <= 0) return '';
  final List<String> words = trim().split(RegExp(r'\s+'));
  if (words.length <= n) return words.join(' ');
  return words.sublist(words.length - n).join(' ');
}