Reputation: 1782
I am accepting values from textfield and want to remove multiple whitespaces from those values and replace them with single one how can I achieve this in dart so far I have tried,
' '.join(mystring.split())
but this seems not to work as it does in python it throws join cannot be performed on string in dart So how can I do it in dart...
Upvotes: 4
Views: 2980
Reputation: 71903
The smallest and simplest solution would be:
final _whitespaceRE = RegExp(r"\s+");
String cleanupWhitespace(String input) =>
input.replaceAll(_whitespaceRE, " ");
You can also use split
/join
:
String cleanupWhitespace(String input) =>
input.split(_whitespaceRE).join(" ");
It's probably slightly less performant, but unless you're doing it all the time, it's not something which is going to matter.
If performance really matters, and you don't want to replace a single space with another single space, then you can change the RegExp to:
final whitespaceRE = RegExp(r"(?! )\s+| \s+");
Very unlikely to matter just for handling user input.
Upvotes: 14
Reputation: 19
def clean_words(Complex_words):
List_words =Complex_words.split()
New_word = ""
for i in List_words:
New_word = New_word + " "+ i
return New_word
Upvotes: 0
Reputation: 6621
Something like:
final newstring = yourstring.replaceAllMapped(RegExp(r'\b\s+\b'), (match) {
return '"${match.group(0)}"';
});
or
final newstring = yourstring.replaceAllMapped(new RegExp(r'/\s+/'), (match) {
return ' ';
});
Upvotes: 0