toSlugWithMaxLength method

  1. @useResult
String toSlugWithMaxLength(
  1. int maxLength
)

Returns a slug with at most maxLength characters, truncating at word boundaries when possible.

If maxLength is less than 1, returns the same as toSlug() with no length limit. Truncation happens at the last hyphen before maxLength; if none, truncates at maxLength. Returns the truncated slug string.

Example:

'Hello World Again'.toSlugWithMaxLength(10); // 'hello-worl'
'a-b-c'.toSlugWithMaxLength(3);             // 'a-b'

Implementation

@useResult
String toSlugWithMaxLength(int maxLength) {
  if (maxLength < 1) return toSlug();
  final String slug = toSlug();
  if (slug.length <= maxLength) return slug;
  final int lastHyphen = slug.lastIndexOf('-', maxLength);
  if (lastHyphen <= 0) return slug.replaceRange(maxLength, slug.length, '');
  return slug.replaceRange(lastHyphen, slug.length, '');
}