removeBetweenAll method

  1. @useResult
String removeBetweenAll(
  1. String start,
  2. String end, {
  3. bool inclusive = true,
})

Returns a new string with all content between start and end delimiters removed.

If inclusive is true (default), the delimiters themselves are also removed.

Implementation

@useResult
String removeBetweenAll(String start, String end, {bool inclusive = true}) {
  if (start.isEmpty) {
    return this;
  }

  if (this == start + end && inclusive) {
    return '';
  }

  // endOptional:false so we only act on a real, closed start..end pair.
  final String found = between(start, end, endOptional: false);
  // Empty content with no literal "startend" adjacency: nothing to strip unless
  // start and end exist separately in order. If they don't, return unchanged so
  // a lone start (or out-of-order delimiters) is never partially mangled.
  if (found.isEmpty && !contains(start + end)) {
    if (contains(start) && contains(end) && indexOf(start) < indexOf(end)) {
      if (inclusive && this == start + end) {
        return '';
      }
    } else {
      return this;
    }
  }
  // Reconstruct the literal span to delete: with the delimiters when inclusive,
  // just the inner content otherwise. An empty non-inclusive pattern would make
  // replaceAll a no-op (or worse), so bail out and return the string untouched.
  final String pattern = inclusive ? (start + found + end) : found;
  if (pattern.isEmpty && !inclusive) {
    return this;
  }

  return replaceAll(pattern, '');
}