Dart – Replace Substring in String
To replace all occurrences of a substring in a string with new substring, use String.replaceAll() method.
Syntax
The syntax of replaceAll() method is:
String.replaceAll(Pattern pattern, String newSubString)
The method returns a new string with all string matchings of given pattern replaced with newSubString. You can also give a string for pattern.
Examples
Replace Substring in String
In this example, we will take a string str, and replace 'Hello' with 'Hi' in the string str.
Dart Program
void main(){
String str = 'Hello TutorialKart. Hello User.';
//replace subString
String result = str.replaceAll('Hello', 'Hi');
print(result);
}
Output
Hi TutorialKart. Hi User.
Now, let us take a string and replace the substring 'Ola' with 'Hi' in the string. But, the string does not contain 'Ola'. Let us see what happens.
Dart Program
void main(){
String str = 'Hello TutorialKart. Hello User.';
//replace subString
String result = str.replaceAll('Ola', 'Hi');
print(result);
}
Output
Hello TutorialKart. Hello User.
Since there is no match for the provided pattern, copy of the original string is returned by replaceAll().
Chaining replaceAll() method
You can chain replaceAll() method. In this example, we will chain replaceAll() method. Please observe the following Dart program.
Dart Program
void main(){
String str = 'Hello TutorialKart. Hello User.';
//replaceAll() chaining
String result = str.replaceAll('Hello', 'Hi').replaceAll('User', 'Client');
print(result);
}
Output
Hi TutorialKart. Hi Client.
First replaceAll() replaces 'Hello' with 'Hi', and then on this resulting string, second replaceAll() replaces 'User' with 'Client'.
Conclusion
In this Dart Tutorial, we learned how to replace all occurrences of a substring with another, in a given string, using String.replaceAll() method.
