Dart String replaceAll()
Syntax & Examples
Syntax of String.replaceAll()
The syntax of String.replaceAll() method is:
String replaceAll(Pattern from, String replace)
This replaceAll() method of String replaces all substrings that match from
with replace
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
from | required | the substring or pattern to search for within the string |
replace | required | the string that replaces each substring or pattern found |
Return Type
String.replaceAll() returns value of type String
.
✐ Examples
1 Replace vowels with asterisks
In this example,
- We create a string
str1
with the value 'Hello, world!'. - We use the
replaceAll()
method with a regular expressionRegExp('[aeiou]')
to match vowels. - We replace each vowel with an asterisk '*' in
str1
. - We print the replaced string to standard output.
Dart Program
void main() {
String str1 = 'Hello, world!';
String replacedStr1 = str1.replaceAll(RegExp('[aeiou]'), '*');
print('Replaced string: $replacedStr1');
}
Output
Replaced string: H*ll*, w*rld!
2 Replace 'D' with asterisk
In this example,
- We create a string
str2
with the value 'ABCDE'. - We use the
replaceAll()
method to replace occurrences of 'D' with an asterisk '*' instr2
. - We print the replaced string to standard output.
Dart Program
void main() {
String str2 = 'ABCDE';
String replacedStr2 = str2.replaceAll('D', '*');
print('Replaced string: $replacedStr2');
}
Output
Replaced string: ABC*E
3 Replace 'ipsum' with 'replacement'
In this example,
- We create a string
str3
with the value 'Lorem ipsum dolor sit amet'. - We use the
replaceAll()
method to replace all occurrences 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.replaceAll('ipsum', 'replacement');
print('Replaced string: $replacedStr3');
}
Output
Replaced string: Lorem replacement dolor sit amet
Summary
In this Dart tutorial, we learned about replaceAll() method of String: the syntax and few working examples with output and detailed explanation for each example.