Search code examples
regexreplacedartflutterwhitespace

How to replace spaces middle of string in Dart?


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

Solution

  • Using RegExp like

    String result = _myText.replaceAll(RegExp(' +'), ' ');