I created a function that uses the indexOf
to find the string to be replaced within the entry and a for
to iterate on it and look for the correct occurrence to be replaced.
Once the part to be replaced is found in the string, the method substring
can be used to mount a new string by concatenating the part of the input that has what is before the chunk to be replaced, the chunk replacement to be replaced and then the part of the input that has what is after the chunk replaced.
If the part to be replaced is not found, the input string is changed inhaled.
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>");
But the substitution is suspected not to differentiate more than minuscule ? When it says replace the second
e
this would actually be the firste
minuscule.– Isac