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

ParameterOptional/RequiredDescription
fromrequiredthe pattern to search for within the string
replacerequireda 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,

  1. We have a string str containing the text 'The price is 20.00'.
  2. We use the replaceAllMapped() method to replace any digit with 'X'.
  3. We define a regular expression to match any single digit (e.g., 2, 0, 8, 7).
  4. The replace function replaces the matched digits in given string with 'X'.
  5. 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,

  1. We have a string str containing the text 'The quick brown fox jumps over the lazy dog'.
  2. We use the replaceAllMapped() method to replace vowels with their uppercase equivalents.
  3. We define a regular expression to match vowels.
  4. The replace function converts the matched vowel to uppercase using match.group(0)!.toUpperCase().
  5. 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,

  1. We have a string str containing the text 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'.
  2. We use the replaceAllMapped() method to replace vowels with asterisks (*).
  3. We define a regular expression to match vowels.
  4. The replace function replaces the matched vowel with '*'.
  5. 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.