How to Capitalize the First Letter of a String using JavaScript?

Today we are going to learn how we can capitalize the First Letter of a String using JavaScript. It is very easy and extremely simple to capitalize the first letter of a String using JavaScript. The only thing that you need to keep in mind is how to use the predefined functions while writing the JavaScript code. For your convenience I will write both the HTML and the JAVASCRIPT codes below, first seperately and then will give you the entire code, so that it is easy for you to understand.

CAPITALIZE THE FIRST LETTER OF A STRING USING JAVASCRIPT

HTML CODE

Here we use the hyperlink tag, so that on clicking “Capitalize String”, the first letter of the string will become capital.



<html>
<head>
<title>Capitalize First Letter in String</title>
</head>
<body>
<div id="myId">hello</div>

<a href='javascript:void(0);' onclick='capitalizeFirst("hello")'>Capitalize String</a>
</body>
</html>

JAVASCRIPT CODE

Here we use the toUpperCase() function to capitalize the first letter of the string. The above function will accept the string and will format it into capitalize form.We can use this function anywhere to capitalize the string. This code needs to be inserted inside the body tag of the above HTML code.

<script type='text/javascript'>
function capitalizeFirst(str) {
    var result = str.charAt(0).toUpperCase() + str.slice(1);
   document.getElementById('myId').innerHTML = result;
}
</script>

ENTIRE CODE to capitalize first letter of a string

<html>
<head>
<title>Capitalize First Letter in String</title>
<script type='text/javascript'>
function capitalizeFirst(str) {
    var result = str.charAt(0).toUpperCase() + str.slice(1);
   document.getElementById('myId').innerHTML = result;
}
</script>

</head>
<body>
<div id="myId">hello</div>

<a href='javascript:void(0);' onclick='capitalizeFirst("hello")'>Capitalize String</a>
</body>
</html>

OUTPUT

Click on Capitalize String

hello

Capitalize String

 

On clicking Capitalize String your result will become

Hello

Capitalize String

 

So you can see how easy and fun this code was. You can try out this example yours and may also read

Leave a Reply

Your email address will not be published. Required fields are marked *