'How to remove all whitespace of a string in Dart?
Using trim() to eliminate white space in Dart and it doesn't work.
What am I doing wrong or is there an alternative?
String product = "COCA COLA";
print('Product id is: ${product.trim()}');
Console prints: Product id is: COCA COLA
Solution 1:[1]
This would solve your problem
String name = "COCA COLA";
print(name.replaceAll(' ', ''));
Solution 2:[2]
the Trim method just remove the leading and trailing. Use Regexp instide: Here is an example: Dart: Use regexp to remove whitespaces from string
Solution 3:[3]
I know that this question has pretty good answers, but I want to show a fancy way to remove all whitespace in a string. I actually thought that Dart should've had a built-in method to handle this, so I created the following extension for String class:
extension ExtendedString on String {
/// The string without any whitespace.
String removeAllWhitespace() {
// Remove all white space.
return this.replaceAll(RegExp(r"\s+"), "");
}
}
Now, you can use it in a very simple and neat way:
String product = "COCA COLA";
print('Product id is: ${product.removeAllWhitespace()}');
Solution 4:[4]
You can try this:
String product = "COCA COLA";
print(product.split(" ").join("")); // COCACOLA
Solution 5:[5]
In case this is of any help to someone in the future, for convenience you can define an extension method to the String class:
extension StringExtensions on String {
String removeWhitespace() {
return this.replaceAll(' ', '');
}
}
This can be called like product.removeWhiteSpace() I've used it in the past to create a helper method when sorting lists by a string whilst ignoring case and whitespace
extension StringExtensions on String {
String toSortable() {
return this.toLowerCase().replaceAll(' ', '');
}
}
Solution 6:[6]
There are so many ways to do this.
The most obvious one:
String product = "COCA COLA";
print('Product id is: ${product.replaceAll(' ', '')}'); // COCACOLA
With regular function:
String removeAllWhitespaces(String string) {
return string.replaceAll(' ', '');
}
String product = "COCA COLA";
print('Product id is: ${removeAllWhitespaces(product)}'); // COCACOLA
With extension method:
extension StringRemoveWhitespace on String {
String get removeAllWhitespaces => replaceAll(' ', ''); // COCACOLA
}
String product = "COCA COLA";
print('Product id is: ${product.removeAllWhitespaces}');
Solution 7:[7]
var s = "Coca Cola"; s.replaceAll(' ','');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christopher Moore |
| Solution 2 | ShrJamal |
| Solution 3 | Stewie Griffin |
| Solution 4 | mdev |
| Solution 5 | Giles Correia Morton |
| Solution 6 | Talat El Beick |
| Solution 7 | Sbr777 |
