Dart String replaceFirst()
Syntax & Examples
Syntax of String.replaceFirst()
The syntax of String.replaceFirst() method is:
String replaceFirst(Pattern from, String to, [int startIndex = 0])
This replaceFirst() method of String creates a new string with the first occurrence of from
replaced by to
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
from | required | the substring or pattern to search for within the string |
to | required | the string that replaces the first occurrence of 'from' |
startIndex | optional [default value is 0] | if provided, matching will start at this index |
Return Type
String.replaceFirst() returns value of type String
.
✐ Examples
1 Replace first 'l' with asterisk
In this example,
- We create a string
str1
with the value 'Hello, world!'. - We use the
replaceFirst()
method to replace the first occurrence of 'l' with an asterisk '*' instr1
. - We print the replaced string to standard output.
Dart Program
void main() {
String str1 = 'Hello, world!';
String replacedStr1 = str1.replaceFirst('l', '*');
print('Replaced string: $replacedStr1');
}
Output
Replaced string: He*lo, world!
2 Replace first 'C' with asterisk
In this example,
- We create a string
str2
with the value 'ABCDECCE'. - We use the
replaceFirst()
method to replace the first occurrence of 'C' with an asterisk '*' instr2
. - We print the replaced string to standard output.
Dart Program
void main() {
String str2 = 'ABCDECCE';
String replacedStr2 = str2.replaceFirst('C', '*');
print('Replaced string: $replacedStr2');
}
Output
Replaced string: AB*DECCE
3 Replace first 'ipsum' with 'replacement'
In this example,
- We create a string
str3
with the value 'Lorem ipsum dolor sit amet'. - We use the
replaceFirst()
method to replace the first occurrence of 'ipsum' with 'replacement' instr3
. - We print the replaced string to standard output.
Dart Program
void main() {
String str3 = 'Lorem ipsum dolor sit amet';
String replacedStr3 = str3.replaceFirst('ipsum', 'replacement');
print('Replaced string: $replacedStr3');
}
Output
Replaced string: Lorem replacement dolor sit amet
Summary
In this Dart tutorial, we learned about replaceFirst() method of String: the syntax and few working examples with output and detailed explanation for each example.