replaceLastNCharacters method

  1. @useResult
String replaceLastNCharacters(
  1. int n,
  2. String replacementChar
)

Returns a new string with the last n characters (grapheme clusters) replaced by replacementChar.

Counts user-perceived characters, so a trailing emoji or base letter plus combining mark counts as one. Returns this string unchanged when n is zero, negative, or greater than the grapheme count.

Example:

'12345'.replaceLastNCharacters(2, '*'); // '123**'
'ab👋'.replaceLastNCharacters(1, '*');  // 'ab*'

Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String replaceLastNCharacters(int n, String replacementChar) {
  // Grapheme count, not code-unit `length`: substringSafe is grapheme-indexed,
  // so `length - n` kept too many characters when the string held emoji.
  final int graphemeCount = characters.length;
  if (n <= 0 || n > graphemeCount) {
    return this;
  }

  return substringSafe(0, graphemeCount - n) + replacementChar * n;
}