I created a function that uses indexOf
to look for the string to be replaced inside the entry and a for
to iterate through it and look for the correct occurrence to be replaced.
Once the part to be replaced is found in the string, the substring
method can be used to assemble a new string by concatenating the part of the input that has what is before the piece to be replaced, the substitute of the piece to be replaced and then the part of the entry that has what is there after the replaced passage.
If the part to be replaced is not found, the input string is changed invalid.
Follow the function code along with the corresponding test code:
function substituir(entrada, substituindo, substituto, ordem) {
if (ordem === 0) return entrada;
var upEntrada = entrada.toUpperCase();
var upSubstituindo = substituindo.toUpperCase();
var idx = -1;
for (var i = 0; i < ordem; i++) {
idx = upEntrada.indexOf(upSubstituindo, idx + 1);
if (idx === -1) return entrada;
}
return entrada.substring(0, idx)
+ substituto
+ entrada.substring(idx + substituindo.length);
}
var teste1 = "Eletricidade";
var saida1 = substituir(teste1, "e", "", 2);
document.write(teste1 + " - " + saida1 + "<br>");
var teste2 = "Ana, Mariana e Luciana gostam de comer banana.";
var saida2 = substituir(teste2, "ana", "mara", 3);
document.write(teste2 + " - " + saida2 + "<br>");
var teste3 = "Azul Verde Vermelho Lilás Verde Roxo";
var saida3 = substituir(teste3, "verde", "Branco", 0);
var saida4 = substituir(teste3, "verde", "Branco", 1);
var saida5 = substituir(teste3, "verde", "Branco", 2);
var saida6 = substituir(teste3, "verde", "Branco", 3);
document.write(teste3 + " - " + saida3 + "<br>");
document.write(teste3 + " - " + saida4 + "<br>");
document.write(teste3 + " - " + saida5 + "<br>");
document.write(teste3 + " - " + saida6 + "<br>");
var teste7 = "AAAAAAAAAAAAAAAAAAAA";
var saida7 = substituir(teste7, "X", "Y", 2);
var saida8 = substituir(teste7, "A", "Z", 999);
var saida9 = substituir(teste7, "A", "Z", 5);
document.write(teste7 + " - " + saida7 + "<br>");
document.write(teste7 + " - " + saida8 + "<br>");
document.write(teste7 + " - " + saida9 + "<br>");