Capitalize First Letter of a String in JavaScript


In this article, we will learn how to convert the first letter of a string to uppercase in JavaScript.

In JavaScript, we have to use the combination of few methods like charAt(), slice() and toUpperCase() to make the first letter of a string to uppercase.

Capitalize the First Letter of a String

To capitalize the first letter of a given string we will use three functions: charAt(), toUpperCase() and slice().

chartAt()

The charAt() method return the character at a specific index in the string. To get the first letter from a string, we use charAt(0).

var str = "hello"
str.charAt(0)

//Output - h

toUpperCase()

The toUpperCase() is an inbuilt method that converts the characters of a string to uppercase letters in JavaScript.

var str = "hello"
str.toUpperCase()
// HELLO

slice()

The slice() method is use to extract parts from a string and returns the rest of the string as a new string.

var str = "Hello world!"; 
str.slice(3); // Extract first 3 characters from the string
// lo world!

Using these three methods, we can create a function that will take a string as an argument, convert its first letter to uppercase and return back the string.

function capitalize( str ){
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
 }
 
console.log(capitalize('hello')) // Hello

Code Explanation:

str.charAt(0) - Extract the first letter of the string i.e 'h' from the word 'hello'.

str.charAt(0).toUpperCase() - Converts h to capital H.

str.slice(1) : extract the first letter and returns the rest of the string. Here it gives us ello from the word 'hello'.

toLowerCase() : to convert the string to lower case.

The + to concat the two values together.

Using Bracket Notion to convert letter to uppercase

Instead of charAt(), we can also use the bracket notion to extract the first letter from a string.

function capitalize(str) {
  return str[0].toUpperCase() + str.slice(1).toLowerCase();
}

console.log(capitalize('hello')) // Hello

Using Regex to Convert First Letter to UpperCase

This is a very simple way, here we replace the first character of the string after converting the first letter to uppercase using regex.

function capitalize(str) {
  return str.replace(/^./, str.charAt(0).toUpperCase());
}

console.log(capitalize('hello')) // Hello

Code Explanation:

replace() - search for the regular expression and returns a new string with replaced value.

The regex expression /^./ matches the beginning of input i.e the first character of the string.

charAt(0) - extract the first letter from the given string.

toUpperCase() - convert the letter to uppercase.

Related Topics:

Truncate A String In JavaScript With Example

How To Convert An Array To String In Javascript

How To Remove Last Character From A String In Javascript


💾 Recommended Articles