Snake Case คือรูปแบบการเขียนสตริงที่แทนที่ช่องว่างด้วยขีดล่าง (_) และแปลงตัวอักษรทั้งหมดเป็นตัวพิมพ์เล็ก
ตัวอย่าง
// Input: 'This is a simple sentence' // Output: 'this_is_a_simple_sentence'
ตัวอย่างโค้ด
const str = 'This is a simple sentence';
const toSnakeCase = (str = '') => {
// แยกคำด้วยช่องว่าง แปลงเป็นพิมพ์เล็ก แล้วเชื่อมด้วย _
return str.split(' ')
.map(word => word.toLowerCase())
.join('_');
};
console.log(toSnakeCase(str));
วิธีที่ทันสมัยกว่า (Modern Approach)
const toSnakeCase = (str = '') =>
str.trim()
.toLowerCase()
.split(/\s+/) // รองรับช่องว่างหลายช่อง
.join('_');
ผลลัพธ์
this_is_a_simple_sentence
ประยุกต์ใช้: การตั้งชื่อตัวแปรในฐานข้อมูล API endpoints การจัดรูปแบบข้อมูล