replaceLast method

  1. @useResult
String replaceLast(
  1. String pattern,
  2. String replacement
)

Replaces only the last occurrence of pattern with replacement.

Returns this string if pattern is not found or empty. pattern must not be empty.

Throws ArgumentError if pattern is empty.

Example:

'a-b-c'.replaceLast('-', '_');  // 'a-b_c'

Implementation

@useResult
String replaceLast(String pattern, String replacement) {
  if (pattern.isEmpty) {
    throw ArgumentError(_kErrPatternNotEmpty, _kParamPattern);
  }
  final int i = lastIndexOf(pattern);
  if (i < 0) return this;
  return replaceRange(i, i + pattern.length, replacement);
}