Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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."
like image 691
Nick Avatar asked Jan 23 '19 07:01

Nick


People also ask

How do you remove spaces between strings in darts?

trim() removes the spaces from beginning and end of string.

How do you replace a space in a string?

Use the String. replace() method to replace all spaces in a string, e.g. str. replace(/ /g, '+'); . The replace() method will return a new string with all spaces replaced by the provided replacement.

How do you remove the whitespace in the middle of a string?

replace() We can use replace() to remove all the whitespaces from the string.

How do you remove spaces in darts?

To trim leading and trailing spaces or white space characters of a given string in Dart, you can use trim() method of String class.


2 Answers

Using RegExp like

String result = _myText.replaceAll(RegExp(' +'), ' ');
like image 55
Günter Zöchbauer Avatar answered Oct 17 '22 21:10

Günter Zöchbauer


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.

like image 31
Ryan Knell Avatar answered Oct 17 '22 23:10

Ryan Knell