Dart String replaceFirstMapped()
Syntax & Examples

Syntax of String.replaceFirstMapped()

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.

Parameters

ParameterOptional/RequiredDescription
fromrequiredthe pattern to search for within the string
replacerequireda function that computes the replacement string based on the match
startIndexoptional [default value is 0]if provided, matching will start at this index

Return Type

String.replaceFirstMapped() returns value of type String.



✐ Examples

1 Replace First Occurrence of 'world'

In this example,

  1. We have a string str containing the text 'Hello, world!'.
  2. We use the replaceFirstMapped() method to replace the first occurrence of "world" with 'planet'.
  3. We define a regular expression to match 'world'.
  4. The replace function replaces the matched substring with 'planet'.
  5. We print the replaced string to standard output.

Dart Program

void main() {
  String str = 'Hello, world!';
  String replacedStr = str.replaceFirstMapped(RegExp(r'world'), (match) => 'planet');
  print('Replaced string: $replacedStr');
}

Output

Replaced string: Hello, planet!

2 Replace First Uppercase Letter with Lowercase

In this example,

  1. We have a string str containing the text 'ABCDEF'.
  2. We use the replaceFirstMapped() method to replace the first uppercase letter with its lowercase equivalent.
  3. We define a regular expression to match uppercase letters.
  4. The replace function converts the matched letter to lowercase using match.group(0)!.toLowerCase().
  5. We print the replaced string to standard output.

Dart Program

void main() {
  String str = 'ABCDEF';
  String replacedStr = str.replaceFirstMapped(RegExp(r'[A-Z]'), (match) => match.group(0)!.toLowerCase());
  print('Replaced string: $replacedStr');
}

Output

Replaced string: aBCDEF

3 Replace First Word with Asterisks

In this example,

  1. We have a string str containing the text 'Lorem ipsum dolor sit amet'.
  2. We use the replaceFirstMapped() method to replace the first word with asterisks (*).
  3. We define a regular expression to match words.
  4. The replace function replaces the matched word with '*'.
  5. We print the replaced string to standard output.

Dart Program

void main() {
  String str = 'Lorem ipsum dolor sit amet';
  String replacedStr = str.replaceFirstMapped(RegExp(r'[A-Za-z]+'), (match) => '*');
  print('Replaced string: $replacedStr');
}

Output

Replaced string: * ipsum dolor sit amet

Summary

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.