Skip to content

Instantly share code, notes, and snippets.

@sairoko12
Created February 16, 2018 23:10
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 sairoko12/64fe88c34fd31b466f777cecfab94d6d to your computer and use it in GitHub Desktop.
Save sairoko12/64fe88c34fd31b466f777cecfab94d6d to your computer and use it in GitHub Desktop.
Simple function that create slugs
const slugify = text => {
// Use hash map for special characters
let specialChars = {"à":'a',"ä":'a',"á":'a',"â":'a',"æ":'a',"å":'a',"ë":'e',"è":'e',"é":'e', "ê":'e',"î":'i',"ï":'i',"ì":'i',"í":'i',"ò":'o',"ó":'o',"ö":'o',"ô":'o',"ø":'o',"ù":'o',"ú":'u',"ü":'u',"û":'u',"ñ":'n',"ç":'c',"ß":'s',"ÿ":'y',"œ":'o',"ŕ":'r',"ś":'s',"ń":'n',"ṕ":'p',"ẃ":'w',"ǵ":'g',"ǹ":'n',"ḿ":'m',"ǘ":'u',"ẍ":'x',"ź":'z',"ḧ":'h',"·":'-',"/":'-',"_":'-',",":'-',":":'-',";":'-'};
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/./g,(target, index, str) => specialChars[target] || target) // Replace special characters using the hash map
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^-+/, '') // Trim - from start of text
.replace(/-+$/, ''); // Trim - from end of text
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment