Title Case a Sentence
แปลงคำแรกของทุกคำเป็น Uppercase ที่เหลือ Lowercase
Algorithm
- Split String ด้วย Space:
str.split(' ') - Lowercase ทุกคำ:
word.toLowerCase() - Uppercase ตัวแรก:
word[0].toUpperCase() + word.slice(1) - Join กลับ:
words.join(' ')
Implementation
<script>
function titleCase(str) {
return str
.toLowerCase()
.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
console.log(titleCase('tutorix is one of best e-platforms'));
// 'Tutorix Is One Of Best E-platforms'
</script>
ผลลัพธ์
Tutorix Is One Of Best E-platforms
Edge Cases Handling
function titleCaseRobust(str) {
return str
.toLowerCase()
.split(/\s+/) // Split by any whitespace (multiple spaces, tabs)
.filter(Boolean) // Remove empty strings
.map(w => w[0].toUpperCase() + w.slice(1))
.join(' ');
}
titleCaseRobust(' hello WORLD '); // 'Hello World'
Locale-aware (International)
function titleCaseLocale(str, locale = 'en') {
return str
.toLowerCase()
.split(' ')
.map(w => w.replace(/^\p{L}/u, c => c.toLocaleUpperCase(locale)))
.join(' ');
}
CSS Alternative (Display Only)
.title-case { text-transform: capitalize; }
ใช้ CSS สำหรับ Display เท่านั้น ข้อมูลจริงไม่เปลี่ยน