Skip to content

Instantly share code, notes, and snippets.

@dinhquochan
Last active November 8, 2018 04:50
Show Gist options
  • Save dinhquochan/788125643e2491ab7f79cb7b42467f6a to your computer and use it in GitHub Desktop.
Save dinhquochan/788125643e2491ab7f79cb7b42467f6a to your computer and use it in GitHub Desktop.
Generate a URL friendly "slug" from a given string
const sluggify = (title) => {
title = title.replace(/^\s+|\s+$/g, "")
title = title.toLowerCase()
let original = title
let from = "àáảãạäăắằẳẵặâầấẩẫậđèéẻẽẹêềếểễệëìíỉĩịïîòóỏõọöôồốổỗộơờớởỡợùúủũụưừứửữựüûyỳýỷỹỵñç·/_,:;"
let to = "aaaaaaaaaaaaaaaaaadeeeeeeeeeeeeiiiiiiioooooooooooooooooouuuuuuuuuuuuuyyyyyync------"
for (let i=0, l=from.length; i < l; i++) {
title = title.replace(new RegExp(from.charAt(i), "g"), to.charAt(i));
}
title = title.replace(/[^a-z0-9 -]/g, "")
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
if (title.replace(/^-$/g, "") === "") {
title = original
.replace(/\s+/g, "-")
.replace(/-+/g, "-")
}
return title
}
export default sluggify
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment