Dart String replaceAllMapped()
Syntax & Examples
Syntax of String.replaceAllMapped()
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.
Parameters
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 |
Return Type
String.replaceAllMapped() returns value of type String
.
✐ Examples
1 Replace Currency Values
In this example,
- We have a string
str
containing the text 'The price is 20.00'. - We use the
replaceAllMapped()
method to replace any digit with 'X'. - We define a regular expression to match any single digit (e.g., 2, 0, 8, 7).
- The
replace
function replaces the matched digits in given string with 'X'. - We print the replaced string to standard output.
Dart Program
void main() {
String str = 'The price is 20.00.';
String replacedStr = str.replaceAllMapped(RegExp(r'\d'), (match) => 'X');
print('Replaced string: $replacedStr');
}
Output
Replaced string: The price is XX.XX.
2 Replace Vowels with Uppercase
In this example,
- We have a string
str
containing the text 'The quick brown fox jumps over the lazy dog'. - We use the
replaceAllMapped()
method to replace vowels with their uppercase equivalents. - We define a regular expression to match vowels.
- The
replace
function converts the matched vowel to uppercase usingmatch.group(0)!.toUpperCase()
. - We print the replaced string to standard output.
Dart Program
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');
}
Output
Replaced string: ThE qUIck brOwn fOx jUmps OvEr thE lAzy dOg.
3 Replace Vowels with Asterisks
In this example,
- We have a string
str
containing the text 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'. - We use the
replaceAllMapped()
method to replace vowels with asterisks (*). - We define a regular expression to match vowels.
- The
replace
function replaces the matched vowel with '*'. - We print the replaced string to standard output.
Dart Program
void main() {
String str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
String replacedStr = str.replaceAllMapped(RegExp(r'[aeiou]'), (match) => '*');
print('Replaced string: $replacedStr');
}
Output
Replaced string: L*rem *ps*m d*l*r s*t *m*t, c*ns*c*tt*r *d*p*sc*ng *l*t.
Summary
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.