whats wrong with my capitalize letters in words code?

user2755667
function LetterCapitalize(str) { 
  return str.charAt(0).toUpperCase()+ str.slice(1);
  var spaceIndex=str.indexOf(' ');
  var first=str.substring(0,spaceIndex);
  var second=str.substring(spaceIndex+1,str.length)

  return LetterCapitalize(first)+" " + LetterCapitalize(second)
}
console.log(LetterCapitalize("hello world"))

not sure what i did wrong but only H in hello is capitalized

Mike Christensen

When your function is called, the very first thing it's doing is:

return str.charAt(0).toUpperCase()+ str.slice(1);

This returns the first character of the string converted to upper case, plus the rest of the string (as is) starting from index 1.

Since the function returns from there, nothing else in your function is being executed.

How about something like:

function LetterCapitalize(str) { 
    var words = str.split(' '); // create an array of each word
    for(var i = 0; i < words.length; i++) // Loop through each word
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); // capitalize first character of each word

    return words.join(' '); // join the array back into a string
}

Also, if you're simply trying to do this for display purposes, you can use the CSS: text-transform: capitalize;

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related