Skip to content

Instantly share code, notes, and snippets.

@joseluisq
Forked from mathewbyrne/slugify.js
Last active August 3, 2023 17:21
Show Gist options
  • Save joseluisq/819d694db6fd675deae7270b4e55b3ac to your computer and use it in GitHub Desktop.
Save joseluisq/819d694db6fd675deae7270b4e55b3ac to your computer and use it in GitHub Desktop.
Javascript Slugify
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