1

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

Hardik Mehta
  • 2,195
  • 1
  • 11
  • 14
taha khamis
  • 401
  • 4
  • 22
  • `trim()` should not remove stuff in the middle. Can you demonstrate this behaviour with an example? – MMZK1526 Aug 12 '22 at 04:15

5 Answers5

1

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.

Anand
  • 4,355
  • 2
  • 35
  • 45
1

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
}
Jeff Schaller
  • 2,352
  • 5
  • 23
  • 38
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
0

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

preview

Kaushik Chandru
  • 15,510
  • 2
  • 12
  • 30
  • Sorry maybe I was not actually very clear but I also wanted to insure that there will be only one space in the middle when i said "and strict the one in the middle to only one space." cause whaen I tried it with multiple spaces it only remove the ones at the begining and the end – taha khamis Aug 12 '22 at 07:44
  • for example (....AB....CD.....) came out as AB....CD but I wanted it to be AB.CD – taha khamis Aug 12 '22 at 07:46
0

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

Sheetal Savani
  • 1,300
  • 1
  • 7
  • 21
0
 String str = "  AB        CD  ";
  
  str = str.trim();
  while (str.contains("  ")) {
    str = str.replaceAll("  ", " ");
  }
  
  print(str);

enter image description here

stacktrace2234
  • 1,172
  • 1
  • 12
  • 22