replaceLast method
Replaces the last occurrence of from at or after startIndex with
replace.
- A String pattern's last occurrence is the one lastIndexOf finds,
even when it overlaps an earlier one:
'aaa'.replaceLast('aa', 'X')is'aX'. - Any other Pattern (e.g. a RegExp) replaces the last of its non-overlapping matches, the same matches allMatches and replaceAll use.
Throws RangeError if startIndex is outside 0..length.
See: replaceFirst.
Implementation
String replaceLast(Pattern from, String replace, [int startIndex = 0]) {
RangeError.checkValueInInterval(startIndex, 0, length, 'startIndex');
final int start;
final int end;
if (from is String) {
start = lastIndexOf(from);
if (start < startIndex) return this; // Also covers "not found" (-1).
end = start + from.length;
} else {
final match = from.allMatches(this, startIndex).lastOrNull;
if (match == null) return this;
start = match.start;
end = match.end;
}
return substring(0, start) + replace + substring(end);
}