Home > Software engineering >  Function to capitalize the first letter of each word in a string
Function to capitalize the first letter of each word in a string

Time:01-02

I don't know if the way I'm approaching this problem is right:

function capitalizer (string) {
    stringArray = string.split(' ');
    for (let i = 0; i< stringArray.length; i  ) { 
        var firstLetter = stringArray[i].charAt(0);
        var firstLetterCap = firstLetter.toUpperCase();
    } 
    return stringArray.join(' ');
} 
console.log(capitalizer('cat on the mat'));

It just returns the original string back without capitalizing anything.

CodePudding user response:

You better use .map function

function capitalizer (str) {
  return str
    .split(' ')
    .map((word) => word[0].toUpperCase()   word.slice(1))
    .join(' ')
}

As Patrick Roberts mentioned, This code will throw an exception if the string have multiple consecutive spaces.

Using the Regex to extract words and apply the function to each word

function capitalize(str) {
    return str.replace(/\w\S*/g, (txt) => txt.charAt(0).toUpperCase()   txt.substr(1).toLowerCase());
};

CodePudding user response:

If you want to use the original code you have to make sure that the firstLetterCap is used and replaced with each of the first letters.

function capitalizer (string) {
stringArray = string.split(' ');
for (let i = 0; i< stringArray.length; i  ) { 
    var firstLetter = stringArray[i].charAt(0);
    var firstLetterCap = firstLetter.toUpperCase();
    stringArray[i] = firstLetterCap   stringArray[i].slice(1);//cap   everything else
} 
return stringArray.join(' ');
} 
console.log(capitalizer('cat on the mat'));
  • Related