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
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 |
Return Type
String.replaceFirstMapped() returns value of type String
.
✐ Examples
1 Replace First Occurrence of 'world'
In this example,
- We have a string
str
containing the text 'Hello, world!'. - We use the
replaceFirstMapped()
method to replace the first occurrence of "world" with 'planet'. - We define a regular expression to match 'world'.
- The
replace
function replaces the matched substring with 'planet'. - 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,
- We have a string
str
containing the text 'ABCDEF'. - We use the
replaceFirstMapped()
method to replace the first uppercase letter with its lowercase equivalent. - We define a regular expression to match uppercase letters.
- The
replace
function converts the matched letter to lowercase usingmatch.group(0)!.toLowerCase()
. - 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,
- We have a string
str
containing the text 'Lorem ipsum dolor sit amet'. - We use the
replaceFirstMapped()
method to replace the first word with asterisks (*). - We define a regular expression to match words.
- The
replace
function replaces the matched word with '*'. - 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.