A simple search and replace with a regex would also do the job here.
function yellowMaker(word) {
return word.replace(/a(.)e/gs, "[yellow]$1");
}
console.log(yellowMaker("same"));
console.log(yellowMaker("name"));
console.log(yellowMaker("aaee"));
console.log(yellowMaker("abcadefg"));
The only scenario this does not cover is "aaee" which should result in "[yellow]a[yellow]e". However the above solution produces "[yellow]ae" If you do want to cover this scenario you can still use a regular expression, but your current solution might be cleaner.
function yellowMaker(word) {
const regex = /a(.)e/gs;
let match, index = 0, result = "";
while (match = regex.exec(word)) {
result += word.slice(index, match.index) + "[yellow]" + match[1];
index = regex.lastIndex;
regex.lastIndex -= 2;
}
return result + word.slice(index, word.length);
}
console.log(yellowMaker("same"));
console.log(yellowMaker("name"));
console.log(yellowMaker("aaee"));
console.log(yellowMaker("abcadefg"));
The regex s flag is relatively new in JavaScript. If you need something that is more compatible, replace the . with [^] (see: Regular expression syntax cheatsheet) but a lot of people also use [\s\S]. After replacing the . you can drop the s flag.
. without the s flag does not match newline characters. Whereas your current code does match the string "a\ne". If you don't care about newline characters you can leave the . and omit the s flag.
const yellowMaker = word => word.replace(/a(.)e/g, "[yellow]$1");-- doesn't need to be excessively "modern", just use a basic regex instead of manually parsing the string.