Capitalizing first letter of each word JavaScript



We are required to write a JavaScript function that takes in a string of words. The function should construct a new string in which the first letter of each word from the original string is capital.

For example −

If the input string is −

const str = 'this is some random string';

Then the output should be −

const output = 'This Is Some Random String';

Example

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));

Output

And the output in the console will be −

This Is Some Random String

Advertisements