Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การทำ Title Case สำหรับประโยคใน JavaScript

สมมติว่าเราต้องเขียนฟังก์ชันที่รับสตริงเข้ามาและทำให้ตัวอักษรแรกของทุกคำเป็นตัวใหญ่ ส่วนตัวอักษรที่เหลือให้เป็นตัวเล็ก

เช่น หากสตริงนำเข้าเป็น

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