2

How to define trimLeft and trimRight functions for String? I can't find a simple solution to implement them.

My tricky solution is:

String _trimLeft(String str) {
  var s = (str + '.').trim();
  return s.substring(0, s.length-1);
}

String _trimRight(String str) {
  return ('.' + str).trim().substring(1);
}

Is there any 3rd-party libraries for Dart just like commons-lang to java, provides such basic functions?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • 1
    Please star http://dartbug.com/5589 - It should just be there. – lrn Mar 10 '14 at 10:26
  • possible duplicate of [Trimming whitespace in Dart strings from beginning or end](http://stackoverflow.com/questions/14107905/trimming-whitespace-in-dart-strings-from-beginning-or-end) – Günter Zöchbauer Mar 14 '14 at 10:27

2 Answers2

1

Another approach would be to match against a RegExp, but your solution looks simpler.

String _trimLeft(String str) {
  RegExp re = new RegExp(r"^\s*(.+)");
  return re.firstMatch(str).group(1);
}

(This code is untested.)

Edit: This question was asked & answered before. see Trimming whitespace in Dart strings from beginning or end

Dart libraries are managed by pub and available on http://pub.dartlang.org/packages

Community
  • 1
  • 1
Jerry101
  • 12,157
  • 5
  • 44
  • 63
1

See this answer that uses String.replace and a RegExp:

Trimming whitespace in Dart strings from beginning or end

I help maintain a general utility package called Quiver, but it doesn't have trim functions. They would be a great addition.

https://github.com/google/quiver-dart

Community
  • 1
  • 1
Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37