removeAfter method

String removeAfter(
  1. String pattern
)

Removes everything in the String after the first match of the pattern.

Example

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

Implementation

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

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

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

  if (patternWords.isEmpty) {
    return '';
  }
  int indexOfLastPatternWord = this.indexOf(patternWords.last);

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

  return this.substring(0, indexOfLastPatternWord);
}