Created
October 22, 2024 07:33
-
-
Save tuanductran/b48a06cde86a6c4f7fcd4327be3531e1 to your computer and use it in GitHub Desktop.
How to create a slug with just a snippet of TypeScript code
This file contains hidden or 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
| export function slugify(str: string): string { | |
| let formattedSlug = str.toLowerCase(); | |
| const accentMapping: { [key: string]: string } = { | |
| á: "a", | |
| à: "a", | |
| ă: "a", | |
| ắ: "a", | |
| ằ: "a", | |
| ẵ: "a", | |
| ẳ: "a", | |
| â: "a", | |
| ấ: "a", | |
| ầ: "a", | |
| ẫ: "a", | |
| ẩ: "a", | |
| ã: "a", | |
| ả: "a", | |
| ạ: "a", | |
| ặ: "a", | |
| ậ: "a", | |
| đ: "d", | |
| é: "e", | |
| è: "e", | |
| ê: "e", | |
| ế: "e", | |
| ề: "e", | |
| ễ: "e", | |
| ể: "e", | |
| ẽ: "e", | |
| ẻ: "e", | |
| ẹ: "e", | |
| ệ: "e", | |
| í: "i", | |
| ì: "i", | |
| ĩ: "i", | |
| ỉ: "i", | |
| ị: "i", | |
| ó: "o", | |
| ò: "o", | |
| ô: "o", | |
| ố: "o", | |
| ồ: "o", | |
| ỗ: "o", | |
| ổ: "o", | |
| õ: "o", | |
| ỏ: "o", | |
| ơ: "o", | |
| ớ: "o", | |
| ờ: "o", | |
| ỡ: "o", | |
| ở: "o", | |
| ợ: "o", | |
| ọ: "o", | |
| ộ: "o", | |
| ú: "u", | |
| ù: "u", | |
| ũ: "u", | |
| ủ: "u", | |
| ư: "u", | |
| ứ: "u", | |
| ừ: "u", | |
| ữ: "u", | |
| ử: "u", | |
| ự: "u", | |
| ụ: "u", | |
| ý: "y", | |
| ỳ: "y", | |
| ỹ: "y", | |
| ỷ: "y", | |
| ỵ: "y", | |
| }; | |
| for (const [accentedChar, replacement] of Object.entries(accentMapping)) { | |
| const regex = new RegExp(accentedChar, "g"); | |
| formattedSlug = formattedSlug.replace(regex, replacement); | |
| } | |
| formattedSlug = formattedSlug | |
| .replaceAll(/[^0-9a-z\\s-]/g, "") // Removes characters that are not letters, numbers, spaces, or hyphens. | |
| .replaceAll(/\\s+/g, "-") // Replace spaces with dashes. | |
| .replaceAll(/-+/g, "-") // Remove repeated hyphens. | |
| .replaceAll(/^-+|-+$/g, ""); // Remove hyphens at the beginning and end of the string. | |
| return formattedSlug; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment