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
.
Parameter | Optional/Required | Description |
---|---|---|
start | required | the index at which to start replacing |
end | optional [null by default] | the index before which to stop replacing (null means replace until the end) |
replacement | required | the string that replaces the specified range |
String.replaceRange() returns value of type String
.
In this example,
str1
with the value 'Hello, world!'.replaceRange()
method to replace the substring starting at index 2 and ending at index 5 (exclusive) with '***' in str1
.void main() {
String str1 = 'Hello, world!';
String replacedStr1 = str1.replaceRange(2, 5, '***');
print('Replaced string: $replacedStr1');
}
Replaced string: He***, world!
In this example,
str2
with the value 'ABCDE'.replaceRange()
method to replace the substring starting at index 1 and ending at index 3 (exclusive) with '**' in str2
.void main() {
String str2 = 'ABCDE';
String replacedStr2 = str2.replaceRange(1, 3, '**');
print('Replaced string: $replacedStr2');
}
Replaced string: A**DE
In this example,
str3
with the value 'Lorem ipsum dolor sit amet'.replaceRange()
method to replace the substring starting at index 6 and ending at index 11 (exclusive) with '****' in str3
.void main() {
String str3 = 'Lorem ipsum dolor sit amet';
String replacedStr3 = str3.replaceRange(6, 11, '****');
print('Replaced string: $replacedStr3');
}
Replaced string: Lorem **** dolor sit amet
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.