Skip to content

Instantly share code, notes, and snippets.

@silkyland
Last active May 20, 2024 01:32
Show Gist options
  • Save silkyland/004e9c74ed9ed8b76d613bc2e4e48f52 to your computer and use it in GitHub Desktop.
Save silkyland/004e9c74ed9ed8b76d613bc2e4e48f52 to your computer and use it in GitHub Desktop.
Convert string to slug in Thai language for SEO Friendly in JavaScript
/**
* 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"
@prawee
Copy link

prawee commented Jun 19, 2023

ใช้ lodash.kebabCase ก็ได้เช่นเดียวกัน

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment