taha khamis
taha khamis

Reputation: 567

How to trim leading and trailing spaces from a string in flutter

I have a 'textformfeild' that takes strings and I want to trim the white spaces at the begining and the end and strict the one in the middle to only one space.

for example if my string is like this:(....AB....CD.....) where the black dots represent the white spaces.

and I wanna make it look like this:(AB.CD)

any idea on how to do that? this is what I tried to do:

userWeight!.trim()

but this will remove all the white spaces including the one in the middle

Upvotes: 1

Views: 2821

Answers (5)

stacktrace2234
stacktrace2234

Reputation: 1500

 String str = "  AB        CD  ";
  
  str = str.trim();
  while (str.contains("  ")) {
    str = str.replaceAll("  ", " ");
  }
  
  print(str);

enter image description here

Upvotes: 0

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63864

trim will remove left and right spaces. You can use RegExp to remove inner spaces:

void main(List<String> args) {
  String data = "       AB      CD   ";

  String result = data.trim().replaceAll(RegExp(r' \s+'), ' ');

  print(result); //AB CD
}

Upvotes: 3

Anandh Krishnan
Anandh Krishnan

Reputation: 6042

Trim - If you use trim() this will remove only first and end of the white spaces example,

String str1 = "   Hello World  "; 
print(str1.trim()); 

The output will be only = Hello World

For your purpose you may use replaceAll

String str1 = "....AB....CD....."; 
print(str1.replaceAll("....",".")); 

The output will be = ".AB.CD."

If you still want to remove first and last . use substring

String str1 = "....AB....CD....."; 
print(str1.replaceAll("....",".").substring( 1, str1.length() - 1 )); 

The output will be = "AB.CD"

This is what your expected output is.

Upvotes: 1

Sheetal Savani
Sheetal Savani

Reputation: 1428

Trim will only remove the leading and trailing spaces or white space characters of a given string

Refer this for more:

https://api.flutter.dev/flutter/dart-core/String/trim.html

Upvotes: 0

Kaushik Chandru
Kaushik Chandru

Reputation: 17822

Trim will remove white spaces before and after the string..

preview

Upvotes: 0

Related Questions