สมมติว่าเราต้องเขียนฟังก์ชันที่ยอมรับสตริงและเปลี่ยนอักษรตัวแรกของทุกคำในสตริงนั้นให้เป็นตัวพิมพ์ใหญ่ แล้วเปลี่ยนตัวพิมพ์ของตัวอักษรที่เหลือทั้งหมดเป็นตัวพิมพ์เล็ก
ตัวอย่างเช่น หากสตริงอินพุตคือ −
hello world coding is very interesting
ผลลัพธ์ควรเป็น −
Hello World Coding Is Very Interesting
มากำหนดฟังก์ชัน capitaliseTitle() ที่รับสตริงและใช้อักษรตัวแรกของแต่ละคำเป็นตัวพิมพ์ใหญ่และส่งกลับสตริง -
ตัวอย่าง
let str = 'hello world coding is very interesting';
const capitaliseTitle = (str) => {
const string = str
.toLowerCase()
.split(" ")
.map(word => {
return word[0]
.toUpperCase() + word.substr(1, word.length);
})
.join(" ");
return string;
}
console.log(capitaliseTitle(str)); ผลลัพธ์
เอาต์พุตคอนโซลจะเป็น −
Hello World Coding Is Very Interesting