The syntax of String.replaceFirstMapped() method is:
String replaceFirstMapped(Pattern from, String replace(Match match), [int startIndex = 0])
This replaceFirstMapped() method of String replaces the first occurrence of from
in this string.
Parameter | Optional/Required | Description |
---|---|---|
from | required | the pattern to search for within the string |
replace | required | a function that computes the replacement string based on the match |
startIndex | optional [default value is 0] | if provided, matching will start at this index |
String.replaceFirstMapped() returns value of type String
.
In this example,
str
containing the text 'Hello, world!'.replaceFirstMapped()
method to replace the first occurrence of "world" with 'planet'.replace
function replaces the matched substring with 'planet'.void main() {
String str = 'Hello, world!';
String replacedStr = str.replaceFirstMapped(RegExp(r'world'), (match) => 'planet');
print('Replaced string: $replacedStr');
}
Replaced string: Hello, planet!
In this example,
str
containing the text 'ABCDEF'.replaceFirstMapped()
method to replace the first uppercase letter with its lowercase equivalent.replace
function converts the matched letter to lowercase using match.group(0)!.toLowerCase()
.void main() {
String str = 'ABCDEF';
String replacedStr = str.replaceFirstMapped(RegExp(r'[A-Z]'), (match) => match.group(0)!.toLowerCase());
print('Replaced string: $replacedStr');
}
Replaced string: aBCDEF
In this example,
str
containing the text 'Lorem ipsum dolor sit amet'.replaceFirstMapped()
method to replace the first word with asterisks (*).replace
function replaces the matched word with '*'.void main() {
String str = 'Lorem ipsum dolor sit amet';
String replacedStr = str.replaceFirstMapped(RegExp(r'[A-Za-z]+'), (match) => '*');
print('Replaced string: $replacedStr');
}
Replaced string: * ipsum dolor sit amet
In this Dart tutorial, we learned about replaceFirstMapped() method of String: the syntax and few working examples with output and detailed explanation for each example.