I made the function below that removes accents from a string using values from an object:
function remAcentos(p){
var acc = {
// ↓ ↓ ↓ ↓ ↓
'á': 'a', 'â': 'a', 'à': 'a', 'ã': 'a', 'â': 'a',
// ↓ ↓
'é': 'e', 'ê': 'e',
'í': 'i',
// ↓ ↓ ↓
'ó': 'o', 'õ': 'o', 'ô': 'o',
'ú': 'u'
}
return p.replace(/[áàãâéêíóõôú]/g, function(m){
return acc[m];
});
}
console.log(remAcentos('brásíliaóúàô'));
It has a replace
with a regex that matches accented letters and replaces the value of the item in the object and returns the string without the accents.
It works perfect, but I'm intrigued by repetitions and a little bit with the aesthetics of the code (see the indicative arrows in the code) and I think this can be optimized without repetitions.
How could I avoid such repetitions? I thought of something like:
var acc = {
'áâàãâ': 'a',
'éê': 'e',
'í': 'i',
'óôõ': 'o',
'ú': 'u'
}
But if I do this way, how could I get the value of the item in the acc
object when the replace
marries an accented letter?