Improves the removeAccents snippet

This commit is contained in:
danielesreis
2020-10-04 10:40:01 -03:00
parent a7014baab2
commit 2e61a40d15

View File

@ -5,25 +5,11 @@ tags: string,beginner
Removes accents from strings. Removes accents from strings.
- Uses a set of known accents for all vowels. - Converts the string to a normalized Unicode format.
- Iterates through the characters, replacing the accentued ones for its unaccentuated form. - The diacritical marks are represented by an Unicode range and are replaced by empty strings.
```js ```js
const removeAccents = (string) => { const removeAccents = string => string.normalize("NFD").replace(/[\u0300-\u036f]/g, "")
const accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖòóôõöÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûü';
const noAccents = 'AAAAAAaaaaaaOOOOOOoooooEEEEeeeeIIIIiiiiUUUUuuuu';
let splitted = string.split('');
splitted = splitted.map((char) => {
const pos = accents.indexOf(char);
return (pos >= 0 ? noAccents[pos] : char);
});
const newString = splitted.join('');
return newString;
}
``` ```
```js ```js