Skip to content

Instantly share code, notes, and snippets.

@silkyland
Last active May 20, 2024 01:32
Show Gist options
  • Select an option

  • Save silkyland/004e9c74ed9ed8b76d613bc2e4e48f52 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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

.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
Copy Markdown

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

@silkyland
Copy link
Copy Markdown
Author

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

@prawee
Copy link
Copy Markdown

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