Solution:
let input = "§kfoo bar 123 bar baz§rfoo bar 123 bar§kfoo bar 123 barbar baz§r";
let result = replace(input, "§k", "§r", "bar", "BAR");
console.log(input);
console.log(result);
function replace(input, beginStr, endStr, match, replaceWith) {
let beginIndex = input.indexOf(beginStr);
let endIndex = input.indexOf(endStr, beginIndex);
while (beginIndex > -1 && endIndex > -1) {
let matchIndex = input.indexOf(match, beginIndex);
while (matchIndex > beginIndex && matchIndex < endIndex) {
input = input.substring(0, matchIndex) + replaceWith + input.substring(matchIndex + match.length);
matchIndex = input.indexOf(match, beginIndex);
}
beginIndex = input.indexOf(beginStr, endIndex);
endIndex = input.indexOf(endStr, beginIndex);
}
return input;
}
Should output:
§kfoo bar 123 bar baz§rfoo bar 123 bar§kfoo bar 123 barbar baz§r
§kfoo BAR 123 BAR baz§rfoo bar 123 bar§kfoo BAR 123 BARBAR baz§r