The syntax of String.replaceAllMapped() method is:
String replaceAllMapped(Pattern from, String replace(Match match))
This replaceAllMapped() method of String replaces all substrings that match from
by a computed 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 |
String.replaceAllMapped() returns value of type String
.
In this example,
str
containing the text 'The price is 20.00'.replaceAllMapped()
method to replace any digit with 'X'.replace
function replaces the matched digits in given string with 'X'.void main() {
String str = 'The price is 20.00.';
String replacedStr = str.replaceAllMapped(RegExp(r'\d'), (match) => 'X');
print('Replaced string: $replacedStr');
}
Replaced string: The price is XX.XX.
In this example,
str
containing the text 'The quick brown fox jumps over the lazy dog'.replaceAllMapped()
method to replace vowels with their uppercase equivalents.replace
function converts the matched vowel to uppercase using match.group(0)!.toUpperCase()
.void main() {
String str = 'The quick brown fox jumps over the lazy dog.';
String replacedStr = str.replaceAllMapped(RegExp(r'[aeiou]'), (match) => match.group(0)!.toUpperCase());
print('Replaced string: $replacedStr');
}
Replaced string: ThE qUIck brOwn fOx jUmps OvEr thE lAzy dOg.
In this example,
str
containing the text 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'.replaceAllMapped()
method to replace vowels with asterisks (*).replace
function replaces the matched vowel with '*'.void main() {
String str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
String replacedStr = str.replaceAllMapped(RegExp(r'[aeiou]'), (match) => '*');
print('Replaced string: $replacedStr');
}
Replaced string: L*rem *ps*m d*l*r s*t *m*t, c*ns*c*tt*r *d*p*sc*ng *l*t.
In this Dart tutorial, we learned about replaceAllMapped() method of String: the syntax and few working examples with output and detailed explanation for each example.