Last active
November 8, 2018 04:50
-
-
Save dinhquochan/788125643e2491ab7f79cb7b42467f6a to your computer and use it in GitHub Desktop.
Generate a URL friendly "slug" from a given string
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
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