removeLastOccurrence method
Returns a new string with the last occurrence of target removed.
Works on any Unicode content: the match offset is a UTF-16 code-unit index, so it is cut with code-unit String.substring.
Example:
'a-b-c'.removeLastOccurrence('-'); // 'a-bc'
'👋a-b'.removeLastOccurrence('-'); // '👋ab'
Audited: 2026-06-12 11:26 EDT
Implementation
@useResult
String removeLastOccurrence(String target) {
final int lastIndex = lastIndexOf(target);
if (lastIndex == -1) {
return this;
}
// lastIndexOf returns a code-unit offset; the grapheme-indexed substringSafe
// used before misplaced the cut whenever an emoji or combining mark came
// before the match.
return substring(0, lastIndex) + substring(lastIndex + target.length);
}