This article will discuss a general requirement: making only the first letter of a string uppercase in javascript.

Table of Contents:-

Capitalize first letter of a string uppercase using slice() or substring()

Javascript’s slice() method returns a new String object, a portion of the calling string based on indexes passed as arguments. 

Javascript’s substring() method returns a subset of the string between the start and end indexes or to the end of the string. 

See the differences between substring() and slice()

Example:-

Capitalize the first letter of string “javascript is a versatile language”

Code:-

function firstLetterCapitalize(_string) {
    return _string.charAt(0).toUpperCase() + _string.slice(1);
  }

OR

function firstLetterCapitalize(_string) {
    return _string.charAt(0).toUpperCase() + _string.substring(1);
  }

Usage:-

let dummyString = 'javascript is a versatile language';
console.log(firstLetterCapitalize(dummyString));

Output:-

Javascript is a versatile language

Explanation:-

  • Step1: The argument string passed in function firstLetterCapitalize() is the string to be processed. Hence, the first character of this string is capitalised by _string.charAt(0).toUpperCase().
  • Step2: To the new string formed by _string.charAt(0).toUpperCase() rest of the string is added which is other than the first character and is obtained by either _string.substring(1) or _string.slice(1).

Capitalize first letter of a string uppercase using regExp

Regular Expression is used to match a particular text/string with a pattern.

Example:-

Capitalize the first letter of string “javascript is a versatile language”

Code:-

function firstLetterCapitalize(_string) {
    return _string.replace(/^./, _string[0].toUpperCase());
  }

Usage:-

let dummyString = 'javascript is a versatile language';
console.log(firstLetterCapitalize(dummyString));

Output:-

Javascript is a versatile language

Explanation:-

The above code uses the replace() method to get the string’s first character and replace it with its uppercase.

  • / and / mark the beginning and the end of the pattern.
  • ^. specifies to match single character at the beginning of the string.

Read More:

I hope this article helped you to convert the first letter of a string into uppercase. Good Luck!!!