How to remove all whitespace of a string in Dart? How to remove all whitespace of a string in Dart? dart dart

How to remove all whitespace of a string in Dart?


This would solve your problem

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


Try this

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(RegExp(r"\s+"), ""));

Another easy solution:

String name = '4 ever 1 k g @@ @';print(name.replaceAll(' ', '');


  1. Using regular expression (RegExp)

    If the original string contains multiple whitespaces and you want to remove all whitespaces. Apply below solution

    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 this

    print(replaceWhitespacesUsingRegex('One  Two   Three   Four', '')); // Output: 'OneTwoThreeFour'
  2. Using trim()

    trim() method is used to remove leading and trailing whitespaces. It doesn't mutate the original string. If there is no whitespace at the beginning of the end of the String, it will return the original value.

    print('   COCA COLA'.trim()); // Output: 'COCA COLA'print('COCA COLA     '.trim()); // Output: 'COCA COLA'print('   COCA COLA     '.trim()); // Output: 'COCA COLA'
  3. Using trimLeft() and trimRight()

    What if you want to trim at the beginning only but not at the end, or maybe the opposite way. You can use trimLeft for removing leading whitespaces only and trimRight which removes trailing whitespaces only.

    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.

This answer from and author : https://www.woolha.com/tutorials/dart-trim-whitespaces-of-a-string-examples