Dart| Flutter How to: remove all whitespaces or trim in a string

This tutorial shows multiple ways to remove whitespace characters from a given string

How to trim leading and trailing whitespace characters in dart string

The dart string trim method removes the lead and trail whitespace characters. Syntax:

String trim()

Here is an example to remove the start and end whitespace characters from the string

void main() {
  String name = ' Hello Welcome ';
  print(name);

  print(name.trim());
}

Output:

 Hello Welcome
Hello Welcome

It removes any whitespace symbols if the string contains new line (\n) or tab(\t) characters,

void main() {
  String name = ' \tHello Welcome \n';
  print(name);

  print(name.trim());
}

Output:

   Hello Welcome

Hello Welcome

String remove All whitespace in dart

This example uses the String replaceAll method to replace whitespace characters with a blank character

String replaceAll(Pattern from, String replace)

from string is a pattern that replaces the replace string.

It returns the new string

Here is an example

void main() {
  var str = "welcome john";
  print(str); //welcome john

  str = str.replaceAll(" ", "");

  print(str); //welcomejohn
}

Output:

welcome john
welcomejohn

String remove all whitespaces with regular expression

It is using replaceFirst with a regular expression (\\s+)

\\s means white space characters + means one or more characters

Here is an example program

void main() {
  var str = "welcome john";
  print(str); //welcome john

  str = str.replaceFirst(RegExp('\\s+'), "");

  print(str); //welcome jonn
}

Output:

welcome john
welcomejohn

Conclusion

Learn multiple ways to remove all whitespace including begin, middle, and end in a string.