javascriptfunctionreplaceaccent-sensitive

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;

    }

Solution

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