Home > Enterprise >  improve replace function in javascript
improve replace function in javascript

Time:05-02

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;

    }

CodePudding user response:

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("áéíóú"));

CodePudding user response:

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

  • Related