String helpers
- Dart course
- Intermediate
- Lesson 14/116
- 6 min
Add and test string processing methods.
The slugify method
We'll write a slugify method to turn a string into a URL-friendly form. The method lowercases the letters and replaces spaces with hyphens; this makes titles or tags fit for links.
Example: 'Hello World'.toLowerCase().replaceAll(' ', '-') gives 'hello-world'. We'll add this as a String slugify(String text) method on the class. In Dart toLowerCase lowercases letters and replaceAll replaces the first argument with the second. The same shape works for titles, tags and file names.
Method chaining
slugify calls two methods back to back: first toLowerCase(), then replaceAll(...). This method chaining passes the result of each method to the next.
Example: text.toLowerCase().replaceAll(' ', '-'). Here toLowerCase() returns a lowercase String and replaceAll(...) works on that String. The chain can be longer: text.toLowerCase().trim().replaceAll(' ', '-'). Each step applies to the previous result. This shape is a concise way to transform data step by step.
Practice Add slugify to Helper
Keep the existing Helper class. Add a String slugify(String text) { return text.toLowerCase().replaceAll(' ', '-'); } method to the class. In main, create an instance with var h = Helper(); and call print(h.slugify('Hello World')).
Starter code
class Helper {
final String version;
Helper() : version = '1.0';
}
void main() {
var h = Helper();
print(h.version);
}
// Add the slugify method and call it on an instanceSample solution
class Helper {
final String version;
Helper() : version = '1.0';
String slugify(String text) {
return text.toLowerCase().replaceAll(' ', '-');
}
}
void main() {
var h = Helper();
print(h.slugify('Hello World'));
}Expected output
hello-world
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does slugify('Hello World') return?
- HelloWorld
- hello-world Correct answer
- hello_world
- HELLO WORLD
Explanation: toLowerCase lowercases, replaceAll(' ', '-') turns spaces into hyphens.
2 Complete the slugify body
String slugify(String text) {
return text.____(' ', '-');
}
String slugify(String text) {
return text.replaceAll(' ', '-');
}
Explanation: replaceAll replaces the first argument with the second.
3 Match the slugify parts
| Term | Meaning |
|---|---|
slugify |
Method name |
toLowerCase |
Lowercases letters |
replaceAll |
Turns spaces into hyphens |