addBefore method

String addBefore(
  1. String pattern,
  2. String adition
)

Adds a String before the first match of the pattern. The pattern should not be null.

If there is no match, the String is returned unchanged.

Example

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

Implementation

String addBefore(String pattern, String adition) {
  if (this.isBlank) {
    return this;
  }

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

  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) +
      adition +
      this.substring(
        indexOfFirstPatternWord,
        this.length,
      );
}