Dart String replaceRange()
Syntax & Examples


Syntax of String.replaceRange()

The syntax of String.replaceRange() method is:

 String replaceRange(int start, int? end, String replacement) 

This replaceRange() method of String replaces the substring from start to end with replacement.

Parameters

ParameterOptional/RequiredDescription
startrequiredthe index at which to start replacing
endoptional [null by default]the index before which to stop replacing (null means replace until the end)
replacementrequiredthe string that replaces the specified range

Return Type

String.replaceRange() returns value of type String.



✐ Examples

1 Replace substring 'llo' with '***'

In this example,

  1. We create a string str1 with the value 'Hello, world!'.
  2. We use the replaceRange() method to replace the substring starting at index 2 and ending at index 5 (exclusive) with '***' in str1.
  3. We print the replaced string to standard output.

Dart Program

void main() {
  String str1 = 'Hello, world!';
  String replacedStr1 = str1.replaceRange(2, 5, '***');
  print('Replaced string: $replacedStr1');
}

Output

Replaced string: He***, world!

2 Replace substring 'BCD' with '**'

In this example,

  1. We create a string str2 with the value 'ABCDE'.
  2. We use the replaceRange() method to replace the substring starting at index 1 and ending at index 3 (exclusive) with '**' in str2.
  3. We print the replaced string to standard output.

Dart Program

void main() {
  String str2 = 'ABCDE';
  String replacedStr2 = str2.replaceRange(1, 3, '**');
  print('Replaced string: $replacedStr2');
}

Output

Replaced string: A**DE

3 Replace substring 'ipsum ' with '****'

In this example,

  1. We create a string str3 with the value 'Lorem ipsum dolor sit amet'.
  2. We use the replaceRange() method to replace the substring starting at index 6 and ending at index 11 (exclusive) with '****' 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.replaceRange(6, 11, '****');
  print('Replaced string: $replacedStr3');
}

Output

Replaced string: Lorem **** dolor sit amet

Summary

In this Dart tutorial, we learned about replaceRange() method of String: the syntax and few working examples with output and detailed explanation for each example.