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.

Dart



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.

Dart

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

Welcome Geek :)

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

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.