Open In App

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:



Example 1: 

Replacing the substring in the given string.






// Main function
main() {
    String gfg = "Welcome GeeksForGeeks";
      
    //replace substring of the given string
    String result = gfg.replaceAll("GeeksForGeeks", "Geek!");
      
    print(result);
}

Output:

Welcome Geek!

In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!”.

Example 2:

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




// Main function
main() {
    String gfg = "Welcome GeeksForGeeks";
      
    //replace substring of the given string
    String result = gfg.replaceAll("GeeksForGeeks", "Geek!").replaceAll("!", " :)");
      
    print(result);
}

Output:

Welcome Geek :)

In the above example the substring “GeeksForGeeks” is replaced by another string “Geek!” and then “!” is replaced by ” : )”.

Article Tags :