replace
- Dart course
- Beginner
- Lesson 89/116
- 5 min
Learn string modification with replaceAll.
replaceAll
To replace all occurrences inside a string use replaceAll. It returns a new string; the original is untouched. For example "a-b-c".replaceAll("-", "_") gives "a_b_c". Every dash became an underscore.
If you want only the first match replaced there is replaceFirst. The difference matters: replaceAll returns the string unchanged if no match is found; it never throws. So you can use it safely without a guard.
First match vs all
replaceFirst changes only the first match and leaves the rest. "a-a-a".replaceFirst("-", "_") gives "a_a-a". It is useful when you only want to change the first separator in a log line.
replaceAll changes every one: "a-a-a".replaceAll("-", "_") gives "a_a_a". Which one to pick depends on the task. Most of the time replaceAll is what you want, like cleaning spaces in a username all at once. Still, you should know both.
Practice Your turn: replaceAll
Replace every comma in "book,pen,notebook" with ";" and print the result with print.
Starter code
void main() {
// Replace every comma with a semicolon
// Print the result
}Sample solution
void main() {
final list = "book,pen,notebook";
print(list.replaceAll(",", ";"));
}Expected output
book;pen;notebook
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The replaceAll call
final fixed = "a-b-c".____("-", "_");
final fixed = "a-b-c".replaceAll("-", "_");
Explanation: replaceAll turns every dash into an underscore.
2 Which call turns all dashes of "a-a-a" into underscores?
final out = "a-a-a"._____("-", "_");- replaceFirst
- replaceAll Correct answer
- split
- join
Explanation: replaceAll turns every dash into an underscore.
3 Match the replace methods
| Term | Meaning |
|---|---|
replaceAll |
changes every match |
replaceFirst |
changes only the first |
replace |
uses a Map |
replaceAllMapped |
transforms with a function |