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

ทำให้ตัวอักษรแรกของแต่ละคำเป็นตัวใหญ่ใน JavaScript

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

เช่น ถ้าสตริงอินพุตคือ:

const str = 'this is some random string';

ผลลัพธ์ควรเป็น:

const output = 'This Is Some Random String';

ตัวอย่าง

const str = 'this is some random string';
const capitaliseFirst = (str = '') => {
  const strArr = str.split(' ');
  const newArr = strArr.map(word => {
    const newWord = word[0].toUpperCase() + word.substr(1, word.length - 1);
    return newWord;
  });
  return newArr.join(' ');
};
console.log(capitaliseFirst(str));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็นดังนี้:

This Is Some Random String