Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to replace multiple whitespaces with single whitespace in Dart and Flutter

Tags:

dart

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...

like image 282
Mithson Avatar asked Oct 20 '25 04:10

Mithson


1 Answers

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.

like image 190
lrn Avatar answered Oct 22 '25 19:10

lrn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!