replaceLast method
Replaces the last occurrence of the substring from
with to
.
If from
is not found in the string, returns the original string.
Example:
print('Hello World World'.replaceLast('World', 'There')); // Output: 'Hello World There'
Implementation
String replaceLast(String from, String to) {
int lastAsteriskIndex = lastIndexOf(from);
if (lastAsteriskIndex != -1) {
return substring(0, lastAsteriskIndex) + to + substring(lastAsteriskIndex + 1);
} else {
return this;
}
}