To uppercase the first letter of a string in JavaScript, we can use toUpperCase() method. But it will convert the whole string to upper case. To selectively convert the first letter, we need to break the string and pull out the first character from rest of it. Then use toUpperCase() on first character and concatenate it with rest of the string.

const convertFirstCharacterToUppercase = (stringToConvert) => {
  var firstCharacter = stringToConvert.substring(0, 1);
  var restString = stringToConvert.substring(1);

  return firstCharacter.toUpperCase() + restString;
}

If you want to convert first character to uppercase of all the words in the string then –

  • First split the string in words using blank as delimiter.
  • Then call convertFirstCharacterToUppercase() function on all the words.
  • join() words using space as delimiter.
const convertFirstCharacterAllWordsToUppercase = (stringToConvert) => {
  const wordsArray = stringToConvert.split(' ');
  const convertedWordsArray = wordsArray.map(word => {
    return convertFirstCharacterToUppercase(word);
  });

  return convertedWordsArray.join(' ');
}

    Tweet this to help others

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles