4

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

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 ' ';
});

Comments

0
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

1 Comment

this is not a Dart solution. It is Python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.