addAfter method
Adds a String
after 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.addAfter('brother', ' sam '); // returns 'hello brother sam what a day today ';
Implementation
String addAfter(String pattern, String addition) {
if (this.isBlank) {
return this;
}
if (!this.contains(pattern)) {
return this;
}
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 + 1) +
addition +
this.substring(indexOfLastPatternWord + 1, this.length);
}