Strings
Replace First, All, and Mapped
Dart's String is immutable, so every replace method returns a new string instead of mutating the receiver. replaceFirst(pat, sub) swaps only the first occurrence of a pattern, replaceAll(pat, sub) swaps every occurrence, and replaceAllMapped(regex, fn) runs a callback on each RegExp match and joins the callback's return values. The original text is unchanged across all three calls.
Program
Play the program to swap the first red, swap every red, then wrap each word in stars with a regex callback.
string_replace.dart
void main() {
var text = 'red red blue';
var oneSwap = text.replaceFirst('red', 'RED');
var allSwap = text.replaceAll('red', 'RED');
var stars = text.replaceAllMapped(RegExp(r'\w+'), (m) => '*${m.group(0)}*');
print('$oneSwap | $allSwap | $stars');
}
replaceFirst
`text.replaceFirst(pat, sub)` returns a new `String` with only the first occurrence of `pat` replaced by `sub`; later matches are kept.
replaceAll
`text.replaceAll(pat, sub)` returns a new `String` with every occurrence replaced. The original `text` is unchanged because `String` is immutable.
replaceAllMapped
`text.replaceAllMapped(regex, fn)` runs `fn` on each `RegExp` match and joins the returned strings. `fn` receives a `Match`; `m.group(0)` is the whole match.