before method

String? before(
  1. String pattern
)

Returns the String before a specific character

Example

String test = 'brother what a day today';
String beforeString = test.before('brother'); // returns 'hello '

Implementation

String? before(String pattern) {
  if (this.isBlank) {
    return this;
  }

  if (!this!.contains(pattern)) {
    return '';
  }

  List<String> patternWords = pattern.split(' ');

  if (patternWords.isEmpty) {
    return '';
  }
  int indexOfFirstPatternWord = this!.indexOf(patternWords.first);

  if (patternWords.last.length == 0) {
    return '';
  }

  return this!.substring(
    0,
    indexOfFirstPatternWord,
  );
}