Trimming spaces in Dart strings from start to finish

I am very new to Dart and trying to understand some basic libraries. For strings, there is a trim () function. This is good, but are there any obvious ways to trim spaces at the beginning or only at the end of a line? I can not find them. Thanks.

+7
source share
3 answers

There are no special methods to trim only leading or trailing spaces. But they are easy to implement:

/// trims leading whitespace String ltrim(String str) { return str.replaceFirst(new RegExp(r"^\s+"), ""); } /// trims trailing whitespace String rtrim(String str) { return str.replaceFirst(new RegExp(r"\s+$"), ""); } 
+4
source

The MoreDart library has Guava-inspired helpers that allow you to efficiently trim lines from the beginning, end, or both:

 import 'package:more/char_matcher.dart'; ... var whitespace = new CharMatcher.whitespace(); // what to trim whitespace.trimFrom(input); // trim from beginning and end whitespace.trimLeadingFrom(input); // trim from beginning whitespace.trimTrailingFrom(input); // trim from end 
+1
source

We just added trimLeft and trimRight to the quiver today, although it turns out that they are also added to String in a future version of the SDK. Today you can use Quiver.

The difference between these implementations and the Regex-based solution is that the space definition matches the String.trim definition. Regex recognizes fewer whitespace characters.

http://pub.dartlang.org/packages/quiver

+1
source

All Articles