Last active
May 20, 2024 01:32
-
-
Save silkyland/004e9c74ed9ed8b76d613bc2e4e48f52 to your computer and use it in GitHub Desktop.
Convert string to slug in Thai language for SEO Friendly in JavaScript
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
/** | |
* Translates a string to a Thai slug format. | |
* @param {string} inputString - The string to translate. | |
* @returns {string} The translated string. | |
*/ | |
function toThaiSlug(inputString) { | |
// Replace spaces with hyphens | |
let slug = inputString.replace(/\s+/g, '-'); | |
// Translate some characters to Thai | |
slug = slug.replace('%', 'เปอร์เซนต์'); | |
// Remove all non-word characters | |
slug = slug.replace(/[^\p{L}\p{N}\s-]/gu, ''); | |
// Replace multiple hyphens with a single one | |
slug = slug.replace(/--+/, '-'); | |
// Remove any remaining leading or trailing hyphens | |
slug = slug.replace(/^-+|-+$/g, ''); | |
return slug; | |
} | |
// Example usage | |
const inputString = "รักษา ทดสอบ 123 % 19dsadf -0wer .. 'ดินสอ'^^) + 9 +5 -"; | |
const slug = toThaiSlug(inputString); | |
console.log(slug); // Output: "รักษา-ทดสอบ-123-เปอร์เซนต์-19dsadf-0wer-ดินสอ-9-5" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ใช้ lodash.kebabCase ก็ได้เช่นเดียวกัน