How do I replace a specific part of a string?

Asked

Viewed 193 times

1

I would like to know how to replace part of a string, but only part of order N.

For example, replace the second (only) "and" of "electricity".

Input: Electricity

Output: Eltricidade

Maybe it’s simple, but I’m a layman on the subject... I’ve tried to split and replace, couldn’t.

  • But the substitution is suspected not to differentiate more than minuscule ? When it says replace the second e this would actually be the first e minuscule.

2 answers

2

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>");

1

You can do it this way, using Regular Expression with .replace (explanations in the code):

// parâmetros da função:
// t = texto
// x = texto a ser substituído
// y = novo texto
// p = posição da ocorrência
function subs(t,x,y,p){
   var c = 0;                        // contador
   var r = new RegExp(x,'gi');       // regex: busca em todo texto e não diferencia maiúscula de minúscula
   t = t.replace(r, function(m){     // faz o replace
     c++;                            // incrementa o contador
     return (c == p) ? y : m;        // retorna para a função a string substituída na posição desejada
   });                               // se não encontrar ocorrência, retorna o texto original
   return t;                         // retorna o resultado da função
}

// exemplos
console.log( subs("Eletricidade", "e", "", 2) );
console.log( subs("Eletricidade", "e", "X", 1) );
console.log( subs("Eletricidade", "e", "X", 3) );
console.log( subs("Eletricidade", "ic", "IC", 1) );
console.log( subs("Abracadabra", "Bra", "-", 2) );

Clean code (no comments):

function subs(t,x,y,p){
   var c = 0;
   var r = new RegExp(x,'gi');
   t = t.replace(r, function(m){
     c++;
     return (c == p) ? y : m;
   });
   return t;
}

console.log( subs("Eletricidade", "e", "", 2) );
console.log( subs("Eletricidade", "e", "X", 1) );
console.log( subs("Eletricidade", "e", "X", 3) );
console.log( subs("Eletricidade", "ic", "IC", 1) );
console.log( subs("Abracadabra", "bra", "-", 2) );

  • why not everything toUpperCase(). At this hour with this sleep I could see better

  • Where did you see that? rsrs

  • I think I dreamed!! And in the dream I saw things! hahaha

Browser other questions tagged

You are not signed in. Login or sign up in order to post.