-
-
Save joseluisq/819d694db6fd675deae7270b4e55b3ac to your computer and use it in GitHub Desktop.
Javascript Slugify
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
function slugify (text, ampersand = 'and') { | |
const a = 'àáäâèéëêìíïîòóöôùúüûñçßÿỳýœæŕśńṕẃǵǹḿǘẍźḧ' | |
const b = 'aaaaeeeeiiiioooouuuuncsyyyoarsnpwgnmuxzh' | |
const p = new RegExp(a.split('').join('|'), 'g') | |
return text.toString().toLowerCase() | |
.replace(/[\s_]+/g, '-') // Replace whitespace and underscore with single hyphen | |
.replace(p, c => | |
b.charAt(a.indexOf(c))) // Replace special chars | |
.replace(/&/g, `-${ampersand}-`) // Replace ampersand with custom word | |
.replace(/[^\w-]+/g, '') // Remove all non-word chars | |
.replace(/--+/g, '-') // Replace multiple hyphens with single | |
.replace(/^-+|-+$/g, '') // Remove leading and trailing hyphens | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment