Skip to content

Instantly share code, notes, and snippets.

@jotaelesalinas
Created July 16, 2021 08:51
Show Gist options
  • Save jotaelesalinas/43cd304d8156ea20581b83034f63e567 to your computer and use it in GitHub Desktop.
Save jotaelesalinas/43cd304d8156ea20581b83034f63e567 to your computer and use it in GitHub Desktop.
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