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

ParameterOptional/RequiredDescription
fromrequiredthe substring or pattern to search for within the string
replacerequiredthe 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,

  1. We create a string str1 with the value 'Hello, world!'.
  2. We use the replaceAll() method with a regular expression RegExp('[aeiou]') to match vowels.
  3. We replace each vowel with an asterisk '*' in str1.
  4. 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,

  1. We create a string str2 with the value 'ABCDE'.
  2. We use the replaceAll() method to replace occurrences of 'D' with an asterisk '*' in str2.
  3. 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,

  1. We create a string str3 with the value 'Lorem ipsum dolor sit amet'.
  2. We use the replaceAll() method to replace all occurrences 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.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.