19

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

3 Answers 3

46

Using RegExp like

String result = _myText.replaceAll(RegExp(' +'), ' ');
Sign up to request clarification or add additional context in comments.

Comments

9

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.

Comments

0

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/

Comments

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.