OneBite.Dev - Coding blog in a bite size

Replace A Word In A String In Dart

Code snippet for how to Replace A Word In A String In Dart with sample and detail explanation

Manipulating strings is a common operation in developing software applications and Dart programming language makes this task seamless. This article will demonstrate how to replace a word in a string using Dart.

Code snippet: Replacing a Word in a String

Here’s a simple snippet of how this can be done in Dart:

void main() { 
    String greeting = 'Hello, world'; 
    String newGreeting = greeting.replaceAll('world', 'Dart');  
    print(newGreeting); // "Hello, Dart"
} 

Code Explanation for Replacing a Word in a String

This code example works in the following way, step-by-step:

  1. Declare the main function. The execution of every Dart console application starts from the main function.
void main() {
  1. Inside this main function, we define a string variable named greeting and assign it the value ‘Hello, world’.
    String greeting = 'Hello, world'; 
  1. Next, we call the replaceAll method on the string greeting. This method takes in two parameters - the word you want to replace (in this case ‘world’) and the word with which you want to replace (in this case ‘Dart’). Its task is to create a new string where all occurrences of ‘world’ are replaced with ‘Dart’.
    String newGreeting = greeting.replaceAll('world', 'Dart');  
  1. Lastly, we print out the new string newGreeting. It’s important to note that the replaceAll method does not change the original string, rather it returns a new string that is assigned to newGreeting. The original string greeting remains unchanged.
    print(newGreeting); // "Hello, Dart"
} 

That’s it! By following the simple steps above, you can replace any word in a string in Dart. Experiment with the code and replace different words to understand it better.

dart