Dart - Trim Whitespaces of a String Examples

This tutorial shows you how to trim leading and trailing whitespaces of a String in Dart.

If your application needs to get String inputs from user or other services, you can't guarantee that the String doesn't have leading or trailing whitespaces. Sometimes it's better to get rid of them. The below examples show you how to remove those unwanted characters at the beginning and/or the end of a String.

Using trim()

This method is used to remove leading and trailing whitespaces. It doesn't mutate the original string. If there is no whitespace at the beginning or the end of the String, it will return the original value.

What characters are considered as whitespace in Dart? Dart uses the list from Unicode White_Space property version 6.2 and also the BOM character (0xFEFF). You can see the list at the bottom of this tutorial.

  print('   woolha dot com'.trim()); // Output: 'woolha dot com'
  print('woolha dot com     '.trim()); // Output: 'woolha dot com'
  print('   woolha dot com     '.trim()); // Output: 'woolha dot com'

Using trimLeft() and trimRight()

What if you want to trim at the beginning only but not at the end, or maybe the opposite way. You can use trimLeft for removing leading whitespaces only and trimRight which removes trailing whitespaces only.

  print('   woolha dot com     '.trimLeft()); // Output: 'woolha dot com     '
  print('   woolha dot com     '.trimRight()); // Output:'   woolha dot com'

If the String can be null, you can consider using null-aware operator.

  String s = null;
  print(s?.trim());

The above code will return null instead of throwing NoSuchMethodError.

List of Trimmed Characters

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
205F Separator, Space (Zs) MEDIUM MATHEMATICAL SPACE.
3000 Separator, Space (Zs) IDEOGRAPHIC SPACE
FEFF BOM ZERO WIDTH NO_BREAK SPACE

You can also read about: