How to remove all whitespace of a string in Dart?

2020-06-19 03:39发布

问题:

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

回答1:

Try this

String product = "COCA COLA";
print('Product id is: ${product.replaceAll(new RegExp(r"\s+\b|\b\s"), "")}');


回答2:

This would solve your problem

String name = "COCA COLA";
print(name.replaceAll(' ', '');


回答3:

the Trim method just remove the leading and trailing. Use Regexp instide: Here is an example: Dart: Use regexp to remove whitespaces from string



回答4:

Use Trim Function

String name = "Stack Overflow";
print(name.trim());


回答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(' ', '');
  }
}


标签: dart flutter