removeLastChars method
Returns a new string with the last count grapheme clusters removed.
Bounds-safe: a count of zero or negative is a no-op (returns this
string unchanged), and a count greater than or equal to the grapheme
length returns an empty string rather than throwing.
Counts by grapheme cluster (user-perceived characters), not UTF-16 code units, so a trailing emoji or base+combining-mark sequence is removed as a single unit and never split into an orphaned surrogate or a stranded mark.
Example:
'Hello'.removeLastChars(2); // 'Hel'
'a😀'.removeLastChars(1); // 'a' (whole emoji removed, not split)
'Hi'.removeLastChars(5); // ''
'Hi'.removeLastChars(0); // 'Hi'
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String removeLastChars(int count) {
if (count <= 0) {
return this;
}
// Count user-perceived characters, not UTF-16 code units: the slice below
// is grapheme-indexed (substringSafe), so bounding by String.length would
// mix code-unit arithmetic with grapheme indexing and miscount whenever a
// trailing grapheme spans multiple code units (emoji, combining marks).
final int graphemeCount = characters.length;
if (graphemeCount <= count) {
return '';
}
return substringSafe(0, graphemeCount - count);
}