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. Matching and cutting are UTF-16 code-unit based, so an emoji find or emoji content next to find is handled exactly.

Example:

'--a--'.removeLeadingAndTrailing('-');   // 'a'
'👋a👋'.removeLeadingAndTrailing('👋');  // 'a'

Audited: 2026-06-12 11:26 EDT

Implementation

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

  // find.length is a code-unit count (matching startsWith/endsWith), so cut
  // with code-unit substring; the grapheme-indexed substringSafe used before
  // over-cut an emoji find and could loop past the intended span.
  String value = trim ? this.trim() : this;
  while (value.startsWith(find)) {
    value = value.substring(find.length);
    if (trim) value = value.trim();
  }
  while (value.endsWith(find)) {
    value = value.substring(0, value.length - find.length);
    if (trim) value = value.trim();
  }

  return value.isEmpty ? null : value;
}