How to replace spaces middle of string in Dart?

8,117

Solution 1

Using RegExp like

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

Solution 2

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.

Share:
8,117
Nick
Author by

Nick

Updated on December 09, 2022

Comments

  • Nick
    Nick over 1 year

    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."
    
  • Andres Paladines
    Andres Paladines over 2 years
    Thanks a LOT! :D