How to Replace a Substring of a String in Dart?

To replace all the substring of a string we make use of  replaceAll method in Dart. This method replaces all the substring in the given string to the desired substring. Returns a new string in which the non-overlapping substrings matching from (the ones iterated by from.allMatches(this String)) are replaced by the literal string replace.

Syntax: String_name.replaceAll (Old_String_Pattern, New_String_Pattern);

In the above sequence:

String_name is the name of the string in which operation is to be done. It could be the string itself.
Old_String_Pattern is the pattern present in the given string.
New_String_Pattern is the new pattern that is to be replaced with the old pattern.

Example 1: 
Replacing the substring in the given string.

// Main function
main() {
String s = "Welcome to knowledge base";
 
//replace substring of the given string
String result = s.replaceAll("base", "world!");
 
print(result);
}

Example 2:
Using chain of replaceAll() method to change the string in dart.

// Main function
 main() {
     String s = "Welcome to knowlege base";
    //replace substring of the given string 
    String result = s.replaceAll("base", "world!").replaceAll("!", " :)");
    print(result);
 }

Leave a comment

Your email address will not be published. Required fields are marked *