Created
July 16, 2021 08:51
-
-
Save jotaelesalinas/43cd304d8156ea20581b83034f63e567 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const REGEX_NON_ASCII_CHARS = /[\u00A0-\u9999]/g; | |
const REGEX_SPECIAL_CHARS = /[<>"'`&?=\\/()\[\]\{\}\#]/g; | |
let replaceCharWithHtmlEntity = char => `&#${char.charCodeAt(0)};`; | |
let htmlEncode = str => str.replace(REGEX_NON_ASCII_CHARS, replaceCharWithHtmlEntity) | |
.replace(REGEX_SPECIAL_CHARS, replaceCharWithHtmlEntity); | |
let urlEncode = str => encodeURIComponent(str); | |
let slug = str => { | |
str = str.toLowerCase(); | |
let from = 'àáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ', | |
to = 'aaaaaaceeeeiiiidnoooooouuuuyy'; | |
for (let i = 0, l = from.length; i < l; i++) { | |
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); | |
} | |
let translit = { | |
"æ": 'ae', | |
"ß": 'ss', | |
"þ": 'th', | |
}; | |
for (let char in translit) { | |
str = str.replace(new RegExp(char, 'g'), tanslit[char]); | |
} | |
return str.replace(/[^a-z0-9]+/g, ' ') | |
.trim() | |
.replace(/\s+/g, '-'); | |
} | |
export default { | |
htmlEncode, | |
urlEncode, | |
slug | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment