OneBite.Dev - Coding blog in a bite size

Replace Multiple Words In A String In Dart

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

Dart is an object-oriented, class-based programming language used for building web and mobile applications. This article will guide you through the technique of replacing multiple words in a string using Dart.

Code snippet for Word Replacement in Dart

In Dart, to replace multiple words in a string, you can use the replaceAll() method of the String class. Below is an illustrative example:

void main() {

  String originalString = "Hello, Dart is a great language. Dart is fun.";

  String replacedString = originalString.replaceAll("Dart", "JavaScript"); // Replacing 'Dart' with 'JavaScript'

  print(replacedString);
}

In this code, we replace all occurrences of ‘Dart’ in the original string with ‘JavaScript’.

Code Explanation for Word Replacement in Dart

Let’s break down the steps to fully understand how the word replacement code works in Dart:

  1. Step 1: We initialize the originalString variable containing the initial sentence where we’ll make the substitutions.
String originalString = "Hello, Dart is a great language. Dart is fun.";
  1. Step 2: We want to replace ‘Dart’ with ‘JavaScript’. To do this, we use the replaceAll() method and store the result in a new variable, replacedString. The replaceAll() method takes two parameters. The first parameter is the word we want to replace (‘Dart’), and the second parameter is the word we want to replace it with (‘JavaScript’).
String replacedString = originalString.replaceAll("Dart", "JavaScript");
  1. Step 3: Finally, we print out the replacedString to display the result of the operation.
print(replacedString);

After executing this code, “Hello, Dart is a great language. Dart is fun.” is changed to “Hello, JavaScript is a great language. JavaScript is fun.”. This way, you can easily replace multiple words in a string in Dart.

dart