Skip to content

Instantly share code, notes, and snippets.

@silkyland
Last active January 20, 2024 19:15
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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"
@farookphuket
Copy link

ขอบคุณมากๆ เลยครับ คุณช่วยชีวิตผมเลย วันนี้ผมหามาทั้งวันแล้ว

.replace(/[^\u0E00-\u0E7F\w\-]+/g, '')

ผมหาบรรทัดนี้แหละ เลยได้มาแบบนี้ครับ

        makeSlug(){
            let make_slug = this.title.replace(/\s+/g,"-")
            .replace(/[^\u0E00-\u0E7F\w\-]+/g,'')            
            .replace(/\-\-+/g,'-')
            .replace(/^-+/,'')
            .toLowerCase()
           return this.slug = make_slug
        }

my result thai slug

จะได้ประมาณนี้แหละที่ต้องการ ขอบคุณมากๆ ครับ

@moonoise
Copy link

พวก ไม้หันอากาศ ไม้เอก โท ตัวนี้เวลาอยู่บน address ลิ้งจะโดนตัดไหมครับ

@silkyland
Copy link
Author

@moonoise ไม่โดนครับผม

@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