Reputation: 4493
I have string as shown below. In dart trim() its removes the whitespace end of the string. My question is: How to replace spaces middle of string in Dart?
Example-1:
- Original: String _myText = "Netflix.com. Amsterdam";
- Expected Text: "Netflix.com. Amsterdam"
Example-2:
- Original: String _myText = "The dog has a long tail. ";
- Expected Text: "The dog has a long tail."
Upvotes: 19
Views: 15523
Reputation: 31
To replace white space with single space we can iterate through the string and add the characters into new string variable by checking whitespace condition as below code.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
String str = "Dart remove empty space ";
String stringAfterRemovingWhiteSpace = '';
for (int i = 0; i < str.length; i++) {
if (!str[i].contains(' ')) {
stringAfterRemovingWhiteSpace = stringAfterRemovingWhiteSpace + "" + str[i];
}
}
print(stringAfterRemovingWhiteSpace);
}
Originally published at https://kodeazy.com/flutter-remove-whitespace-string/
Upvotes: 0
Reputation: 6322
In my case I had tabs, spaces and carriage returns mixed in (i thought it was just spaces to start)
You can use:
String result = _myText.replaceAll(RegExp('\\s+'), ' ');
If you want to replace all extra whitespace with just a single space.
Upvotes: 9
Reputation: 657338
Using RegExp like
String result = _myText.replaceAll(RegExp(' +'), ' ');
Upvotes: 46