JavaScript

JavaScript Capitalize the First Letter of a String Example

In this example we will check the JavaScript Capitalize the First Letter of a String implementation. JavaScript provides many functions to work with Strings in general. We will leverage a few of them to achieve our aim. There are more than one way of accomplishing the task at hand and we shall take a look at a couple of them.

1. Initial Setup

So, let us dive in and get started. For the purposes of this article I will build a small NodeJS application which will serve our static web page with the example. You do not need knowledge of NodeJS to follow along though. The structure of our project looks like below:

JavaScript Capitalize the First Letter - Project Structure
Project Structure

Our UI would simply let the user type in a string and we will capitalize the first letter of the string and display the result. To go about the same the HTML of our UI would like below:

index.html

 <!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <fieldset>
            <legend>
                <h3>JCG -- JavaScript Capitalize First Letter of String Example</h3>
            </legend>
            <label for="userinput">Please enter text</label>
            <input type="text" id="userinput">
            <button type="button" id="capitalize">Capitalize</button>
            <label for="result">Result</label>
            <span style="font-weight: bold" id="result"></span>
        </fieldset>
        <script src="./myscript.js"></script>
    </body>
</html> 

The above UI looks like below:

JavaScript Capitalize the First Letter

Next, we write code in our JavaScript file myscript.js. We implement two functions, named, capitalizeUsingStringFunctions and capitalizeUsingSliceFunction. We discuss there implementation next

2. Capitalizing Using String Functions

JavaScript provides several methods to work with strings. Of particular interest to us here are the charAt, toUpperCase and substring functions. Since string is treated as an array of character we can use chartAt function to get the character at a particular position within the string.

We will use it to get the first character and then call the toUpperCase function on the return value. This will capitalize the first character next we will append the remaining string extracted using the substring function and return the result to the calling code. Our function looks like below:

myscript.js

function capitalizeUsingStringFunctions(str) {
    return str.charAt(0).toUpperCase() + str.substring(1, str.length);
} 

3. Capitalizing Using Slice Function

Like mentioned before strings in JavaScript are treated as arrays of characters. Thus we can leverage array manipulation functions on strings as well. One in particular, slice, will prove useful to implement our objective here.

We will use the slice method to extract the first character from the string and capitalize it. We will then append this to the remaining string extracted again using slice function and return the result to the calling code. Our function would look like below:

myscript.js

function capitalizeUsingSlice(str) {
    return str.slice(0, 1).toUpperCase() + str.slice(1, str.length);
} 

After implementing the above two methods we will complete the code to call them and display the result. Our completed code would look like below:

myscript.js

let input = document.getElementById("userinput");
let result = document.getElementById("result");
let button = document.getElementById("capitalize");

button.addEventListener("click", function(evt) {
    //result.innerHTML = capitalizeUsingSlice(input.value);
    result.innerHTML = capitalizeUsingStringFunctions(input.value);
});


function capitalizeUsingSlice(str) {
    return str.slice(0, 1).toUpperCase() + str.slice(1, str.length);
}

function capitalizeUsingStringFunctions(str) {
    return str.charAt(0).toUpperCase() + str.substring(1, str.length);
} 

4. Running the Code

When we run the code and hit the url in the browser, we can see our code in action as below:

JavaScript Capitalize the First Letter

As you can see I have entered my name in all lower case. Next I click the Capitalize button to display the Result with initial letter capitalized.

5. Download the Source Code

This was an example on how to capitalize the first letter of a string. To run the project you need to run the below commands at the root of the project

> npm install
> npm start

After this, point the browser to the following URL:

http://localhost:8080

Download
You can download the full source code of this example here: JavaScript Capitalize the First Letter of a String Example

Siddharth Seth

Siddharth is a Software Development Professional with a Master degree in Computer Applications from IGNOU. He has over 14 years of experience. And currently focused on Software Architecture, Cloud Computing, JavaScript Frameworks for Client and Server, Business Intelligence.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button