{

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.

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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example