We can use JavaScript to capitalize the first letter of a string by combining the JavaScript String toUpperCase() and substring() methods.

var theString = "how are you?"
theString = theString.substring(0,1).toUpperCase() + theString.substring(1);

Let’s look at an example below.


We can create a simple function that will use JavaScript to capitalize the first letter of a string.

We can do this by using the JavaScript toUpperCase() and substring() methods.

function capitalizeFirstLetter(theString){
  //This takes the first character of the string and capitalizes it
  theString = theString.substring(0,1).toUpperCase() + theString.substring(1);
}

Using JavaScript to Capitalize the First Letter of a String with a Click

In this simple example, we will let the user input a string, and we will capitalize the first letter of it.

Here is the HTML setup:

Capitalize First Letter

We will add an onclick event to our #click-me div that will run a function we will create. Our function will first use the value property along with the getElementById method to get the string the user has entered.

We will then convert the first character to uppercase using the String toUpperCase() method.

We will finally post the results using the textContent property.

function capitalizeFirstLetter(){
  
  //Get the user string
  var userString = document.getElementById("string1").value;
  
  //Capitalize the first letter of the string
  userString = userString.substring(0,1).toUpperCase() + userString.substring(1);

  //Display the results
  document.getElementById("results").textContent = userString;

};

The final code and output for capitalizing the first letter of a string in JavaScript is below:

Code Output:


Capitalize First Letter

Full Code:

Capitalize First Letter
<script> function capitalizeFirstLetter(){ var userString = document.getElementById("string1").value; userString = userString.substring(0,1).toUpperCase() + userString.substring(1); document.getElementById("results").textContent = userString; }; </script>

Hopefully this article has been useful for you to learn how to use JavaScript to capitalize the first letter of a string.

Categorized in:

JavaScript,

Last Update: March 14, 2024