Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WagnerMoreira/952704ee8887c9dd34e99d4c535b1ba9 to your computer and use it in GitHub Desktop.
Save WagnerMoreira/952704ee8887c9dd34e99d4c535b1ba9 to your computer and use it in GitHub Desktop.
An Javascript function to remove accents and others characters from an input string.
// Example: https://codepen.io/marcelo-ribeiro/pen/OJmVOyW
const accentsMap = new Map([
["A", "Á|À|Ã|Â|Ä"],
["a", "á|à|ã|â|ä"],
["E", "É|È|Ê|Ë"],
["e", "é|è|ê|ë"],
["I", "Í|Ì|Î|Ï"],
["i", "í|ì|î|ï"],
["O", "Ó|Ò|Ô|Õ|Ö"],
["o", "ó|ò|ô|õ|ö"],
["U", "Ú|Ù|Û|Ü"],
["u", "ú|ù|û|ü"],
["C", "Ç"],
["c", "ç"],
["N", "Ñ"],
["n", "ñ"]
]);
const reducer = (acc, [key]) => acc.replace(new RegExp(accentsMap.get(key), "g"), key);
export const removeAccents = (text) => [...accentsMap].reduce(reducer, text);
export const slugify = text => text
.replace(/\s|_|\(|\)/g, "-")
.normalize("NFD").replace(/\p{Diacritic}/gu, "")
.toLowerCase()
// Example: https://codepen.io/marcelo-ribeiro/pen/PomqOvE
const accentsMap = new Map([
["-", "\\s|\\.|_"],
["a", "á|à|ã|â|ä"],
["e", "é|è|ê|ë"],
["i", "í|ì|î|ï"],
["o", "ó|ò|ô|õ|ö"],
["u", "ú|ù|û|ü"],
["c", "ç"],
["n", "ñ"]
]);
const reducer = (acc, [key]) => acc.replace(new RegExp(accentsMap.get(key), "gi"), key);
export const slugify = (text) => [...accentsMap].reduce(reducer, text.toLowerCase());
export const removeAccents = text => text.normalize("NFD").replace(/\p{Diacritic}/gu, "")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment