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