Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
improve replace function in javascript

I am trying to perform this function in a cleaner way, could you give me a hand?

  function removeAccents(text) {

        var text = text.replace(/á/g, "a").replace(/é/g, "e").replace(/í/g, "i").replace(/ó/g, "o").replace(/ú/g, "u");

        return cadenaTexto;

    }
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your code already looks pretty clean to me, maybe you could put the replaces on separate lines, but it's easy to understand.

I'm not sure if the below code is any cleaner, but I'm just taking advantage of how you can pass a replacerFunction to String.prototype.replace

So that you can keep which characters you want to replace with which into a separate object and just pass them in.

function removeAccents(text) {
  const replacements = { á: "a", é: "e", í: "i", ó: "o", ú: "u" };
  return text.replace(/[áéíóú]/g, match => replacements[match]);
}

console.log(removeAccents("áéíóú"));

about 4 years ago · Juan Pablo Isaza Relatório

0

EDIT: @Ryan White's Solution, using the match callback is by far the fastest solution being from 20% for shorter strings to more than 100% for longer ones, faster than both below solutions since it permits to avoid loops:

const replacements = { à: 'a', è: 'e', ì: 'i', ò: 'o', ù: 'u' };

function removeAccents3(text) {
  const accs = Object.keys(replacements).join('')
  return text.replace(
    new RegExp(`[${accs}]`, 'gi'),
    (match) => replacements[match]
  );
}

console.log(removeAccents3('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 69059.40 ops/s

I propose a couple of approaches, they have similar performances, the replace through RegExp is more performant though, with short strings you don't notice it, but with longer ones you have a +20% of performance.

const accents = [
  {
    val: 'à',
    repl: 'a',
  },
  {
    val: 'è',
    repl: 'e',
  },
  {
    val: 'ì',
    repl: 'i',
  },
  {
    val: 'ò',
    repl: 'o',
  },
  {
    val: 'ù',
    repl: 'u',
  },
];

const removeAccents = (text) => {
  for (const a of accents) text = text.replace(new RegExp(a.val, 'ig'), a.repl);
  return text;
};

console.log("First test:", removeAccents('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 46168.04 ops/s

// 2

const accents2 = {
  à: 'a',
  è: 'e',
  ì: 'i',
  ò: 'o',
  ù: 'u',
};
const removeAccents2 = (text) => text.split("").map(c => accents2[c] ? accents2[c] : c).join("")

console.log("Second test:", removeAccents2('àèbgòè+àòètrysàùì')); //aebgoe+aoetrysaui
// Performance : 45910.35 ops/s

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda