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