between method

  1. @useResult
String between(
  1. String start,
  2. String end, {
  3. bool endOptional = true,
  4. bool trim = true,
})

Returns the content between the first occurrence of start and end.

If endOptional is true (default) and end is not found, returns content after start. When trim is true (default), the result is trimmed. Returns an empty string if no match is found.

An empty end is treated the same as a delimiter that is not found: it never matches, so the endOptional rules apply. With the default endOptional: true this returns everything after start; with endOptional: false it returns an empty string. (BUG-029)

Implementation

@useResult
String between(String start, String end, {bool endOptional = true, bool trim = true}) {
  if (isEmpty || start.isEmpty) {
    return '';
  }

  final int startIndex = indexOf(start);
  if (startIndex == -1) {
    return '';
  }

  final int endIndex = end.isEmpty ? -1 : indexOf(end, startIndex + start.length);
  if (endIndex == -1) {
    if (endOptional) {
      final String content = substringSafe(startIndex + start.length);

      return trim ? content.trim() : content;
    }

    return '';
  }
  final String content = substringSafe(startIndex + start.length, endIndex);

  return trim ? content.trim() : content;
}