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
Try this
String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
This would solve your problem
String name = "COCA COLA";
print(name.replaceAll(' ', '');
the Trim method just remove the leading and trailing. Use Regexp instide:
Here is an example:
Dart: Use regexp to remove whitespaces from string
Use Trim Function
String name = "Stack Overflow";
print(name.trim());
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(' ', '');
}
}