How to uppercase the first letter of a string in JavaScript?

Total
0
Shares

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

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like

.map is not a function

map() can only be used with Arrays. So, if you are getting error .map is not a function, you are probably using it on either the objects or other variables…
View Post

React convert JSON to CSV

React convert JSON to CSV using JSONToCSVConvertor function. Suppose you have a table (GUI react table tool) and you want to export it into excel, then this function will come…
View Post