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

ParameterOptional/RequiredDescription
fromrequiredthe substring or pattern to search for within the string
torequiredthe string that replaces the first occurrence of 'from'
startIndexoptional [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,

  1. We create a string str1 with the value 'Hello, world!'.
  2. We use the replaceFirst() method to replace the first occurrence of 'l' with an asterisk '*' in str1.
  3. 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,

  1. We create a string str2 with the value 'ABCDECCE'.
  2. We use the replaceFirst() method to replace the first occurrence of 'C' with an asterisk '*' in str2.
  3. 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,

  1. We create a string str3 with the value 'Lorem ipsum dolor sit amet'.
  2. We use the replaceFirst() method to replace the first occurrence of 'ipsum' with 'replacement' in str3.
  3. 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.