truncateOnWord method
Truncates the string to a specified maximum number of characters.
If the string is blank, or if maxChars
is less than or equal to 0, or if
maxChars
is greater than the length of the string, the function returns
an empty string or the original string if it is not null.
If the length of the string is less than or equal to maxChars
, the
function returns the original string.
If the string is truncated, an optional ellipsis (...
) can be appended
to the truncated string by setting the ellipsis
parameter to true
.
-
Parameters:
- maxChars: The maximum number of characters to keep in the string.
- ellipsis: A boolean value indicating whether to append an ellipsis
(
...
) to the truncated string. Defaults tofalse
.
-
Returns: The truncated string, optionally with an ellipsis appended.
Implementation
String truncateOnWord(int maxChars, [bool ellipsis = false]) {
if (isBlank || maxChars <= 0 || maxChars > length) {
return blankIfNull;
}
if (length <= maxChars) {
return this;
}
int index = lastIndexOfAny(wordSplitters, maxChars);
if (index == -1) {
return blankIfNull;
}
return first(index) + (ellipsis ? '...' : '');
}