How to Remove All Whitespace of a String In Dart?
Earlier we have been through various articles like how to format an interpolated string in flutter so in this article we will go through how to remove all whitespace of a string in dart?
Flutter Agency
Earlier we have been through various articles like how to format an interpolated string in flutter so in this article we will go through how to remove all whitespace of a string in dart?
How to Remove All Whitespace of a String In Dart?
User can try the below solutions:
String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');
Update:
String name = '4 ever 1 k g @@ @';
print(name.replaceAll(new RegExp(r"\s+"), ""));
This would solve your problem
String name = "COCA COLA";
print(name.replaceAll(' ', ''));
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(' ', '');
}
}
- print(' COCA COLA'.trim()); // Output: 'COCA COLA'
print('COCA COLA '.trim()); // Output: 'COCA COLA'
print(' COCA COLA '.trim()); // Output: 'COCA COLA' - print(' COCA COLA '.trimLeft()); // Output: 'COCA COLA '
print(' COCA COLA '.trimRight()); // Output:' COCA COLA'If the String can be null, you can consider using the null-aware operator.String s = null;
print(s?.trim());The above code will return null instead of throwing NoSuchMethodError. - String replaceWhitespacesUsingRegex(String s, String replace) {
if (s == null) {
return null;
}
// This pattern means "at least one space, or more"
// \\s : space
// + : one or more
final pattern = RegExp('\\s+');
return s.replaceAll(pattern, replace);
}Call like a below:print(replaceWhitespacesUsingRegex('One Two Three Four', '')); // Output: 'OneTwoThreeFour'
Conclusion:
Thanks for being with us on a Flutter Journey !!!
In this article, we have been through how to remove all whitespace of a string in dart?
FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.
Upvote
Flutter Agency
Flutter Agency is the US Leading Flutter app development company build innovative and cutting-edge desktop apps and mobile apps using Flutter framework. Contact us today to get started!
Related Articles