trimAll property

String get trimAll

Trims leading and trailing spaces from the String, so as extra spaces in between words.

Example

String text = '    esentis    thinks   ';
String trimmed = text.trimAll ; // returns 'esentis thinks'

Implementation

String get trimAll {
  if (isBlank) {
    return blankIfNull;
  }
  return splitLines.where((x) => x.isNotBlank).map((value) {
    // Remove spaces before any of this chars (using replaceAllMapped):
    //:,.;?!.,)]}
    value = value.replaceAllMapped(RegExp(r'\s+([\%:,.;?!\)\]})])'), (match) {
      return match.group(1) ?? '';
    });

    // Remove spaces after any of this chars (using replaceAllMapped):
    // ([{
    value = value.replaceAllMapped(RegExp(r'([\(\[\{])\s+'), (match) {
      return match.group(1) ?? '';
    });

    // Remove extra spaces between words
    value = value.replaceAll(RegExp(r'\s+'), ' ');

    return value.trim();
  }).join("\r\n");
}