Dart/Flutter - Replace Multiple Whitespaces with a Single Space

This tutorial shows you how to replace two or more whitespaces in a Dart string to a single whitespace, which also works in Flutter or any other Dart framework.

In some cases, you may have a string where the number spaces between words is more than one. Usually, it's from an external source that you cannot control, such as a response from an API. To make it tidier, you want to remove those excessive whitespaces. In Dart, it can be done by using a simple regex. Below are the examples of how to do it along with the results.

For example, there is a string as shown below.

  var text = '   Hello        World      by Woolha.com  ';

The expected result is the following.

  '   Hello World by Woolha.com  ' (if leading and trailing whitespaces are not removed)
  'Hello World by Woolha.com' (if leading and trailing whitespaces are removed)

Using Regex

Dart's string class has a method named trim() which returns a new string without any leading and trailing whitespace. However, it only handles the whitespaces at the start and the end of a string. It cannot replace those in the middle of the string located between words.

A possible solution is by using a regular expression. Like other programming languages, Dart supports pattern matching. You can define a pattern using the RegExp.

  final regex = RegExp(r'\s+');

Then, call the replaceAll method of the String class by passing the regex as the first argument and the replacement as the second argument. In this case, the replacement is a space.

  print(text.replaceAll(regex, ' '))


  ' Hello World by Woolha.com '

In the output, we can see that the multiple whitespaces have been replaced. However, there are spaces at the beginning and at the end of the string. If you want to remove them, you can call the trim method as well.

  print(text.trim().replaceAll(regex, ' '));


  'Hello World by Woolha.com'

The above methods replace all whitespace characters. The list can be seen below.

Character Category Name
0009..000D Other, Control (Cc) <control-0009>..<control-000D>
0020 Separator, Space (Zs) SPACE
0085 Other, Control (Cc) <control-0085>
00A0 Separator, Space (Zs) NO-BREAK SPACE
1680 Separator, Space (Zs) OGHAM SPACE MARK
2000..200A Separator, Space (Zs) EN QUAD..HAIR SPACE
2028 Separator, Line (Zl) LINE SEPARATOR
2029 Separator, Paragraph (Zp) PARAGRAPH SEPARATOR
202F Separator, Space (Zs) NARROW NO-BREAK SPACE
3000 Separator, Space (Zs) IDEOGRAPHIC SPACE

If you only want to replace spaces, you can change the regex to the following one.

  final regex = RegExp(r'\ +');


This tutorial shows you how to replace multiple whitespaces to a single space in a string using Dart. Basically, you can use a regular expression for it. You can also replace the leading and trailing spaces if necessary by using the trim method.

You can also read about: