Reputation:
I am very new to Dart and am trying to get some sense of the basic libraries. For strings, there is a trim() function provided. This is good, but are there no obvious ways to trim whitespace only at the beginning or only at the end of a string? I cannot find them.Thank you.
Upvotes: 8
Views: 3388
Reputation: 11171
We just added trimLeft
and trimRight
to Quiver today, though it turns out that they are also being added to String
in future SDK release. You can use Quiver today though.
The difference between these implementations and the Regex-based solution is that the definition of whitespace is the same as String.trim
. Regex's recognize fewer whitespace characters.
http://pub.dartlang.org/packages/quiver
Upvotes: 1
Reputation: 8947
The library MoreDart has some Guava inspired helpers that allow you to efficiently trim strings from 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
Upvotes: 1
Reputation: 14171
There are no specific methods for trimming only leading or trailing whitespace. But it is quite easy to implement them:
/// 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+$"), "");
}
Upvotes: 13