{

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 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example