removeLeadingAndTrailing method

  1. @useResult
String? removeLeadingAndTrailing(
  1. String? find, {
  2. bool trim = false,
})

Returns a new string with leading and trailing occurrences of find removed, or null if the result is empty.

When trim is true, whitespace is also trimmed between removals.

Implementation

@useResult
String? removeLeadingAndTrailing(String? find, {bool trim = false}) {
  if (isEmpty || find == null || find.isEmpty) {
    return this;
  }

  String value = trim ? this.trim() : this;
  while (value.startsWith(find)) {
    value = value.substringSafe(find.length);
    if (trim) value = value.trim();
  }
  while (value.endsWith(find)) {
    value = value.substringSafe(0, value.length - find.length);
    if (trim) value = value.trim();
  }

  return value.isEmpty ? null : value;
}