How to make first letter of a string uppercase in JavaScript ?
In this article, we will convert the first letter of a string to uppercase in Javascript.
There are a number of ways to capitalize the first letter of the string in JavaScript.
- Using toUpperCase() method
- Using slice() method
- Using charAt() method
- Using replace() method
JavaScript toUpperCase() Function: This function applies on a string and changes all letters to uppercase.
Syntax:
string.toUpperCase()
JavaScript slice() Function: This function applies to a string and slices it according to the passed parameter.
Syntax:
string.slice(start, end)
Example: This example uses the slice() method to convert the first letter to uppercase.
HTML
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Make first letter of a string uppercase</h3> <input id="input" type="text" name="input" /> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id="div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string[0].toUpperCase() + string.slice(1); } </script></body> |
Output:

JavaScript charAt() Function: This charAt() function returns the character at a given position in the string.
Syntax:
string.charAt(index)
Example: This example uses charAT() method to make the first letter of a string uppercase.
HTML
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Make first letter of a string uppercase</h3> <input id="input" type="text" name="input" /> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id="div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.charAt(0).toUpperCase() + string.slice(1); } </script></body> |
Output:

JavaScript replace() Function: This is a built-in function in JavaScript that is used to replace a slice of a string with another string or a regular expression. The original string will not be affected.
Syntax:
str.replace(A, B)
The below examples show the conversion to uppercase using the above-described methods.
Example: This example uses string.replace() method to make the first letter of a string uppercase.
HTML
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Make first letter of a string uppercase</h3> <input id="input" type="text" name="input" /> <button onclick="capitalizeFLetter()"> Click to capitalize </button> <h3 id="div" style="color: green"> </h3> <script> function capitalizeFLetter() { var input = document.getElementById("input"); var x = document.getElementById("div"); var string = input.value; x.innerHTML = string.replace(/^./, string[0].toUpperCase()); } </script></body> |
Output:




Please Login to comment...