stripSubstring method

  1. @useResult
String stripSubstring(
  1. String substring
)

Removes leading and trailing occurrences of substring until none remain. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
String stripSubstring(String substring) {
  // An empty substring must short-circuit: startsWith('') / endsWith('') are
  // always true, so the loops below would never terminate.
  if (substring.isEmpty) return this;
  String current = this;
  // Peel repeated leading copies, then repeated trailing copies, so e.g.
  // stripping "ab" from "abababXabab" removes every bounding copy, not just one.
  while (current.startsWith(substring)) {
    current = current.substringSafe(substring.length);
  }
  while (current.endsWith(substring)) {
    current = current.substringSafe(0, current.length - substring.length);
  }
  return current;
}