How to use .toUpperCase() – Build a JavaScript Application

The .toUpperCase() function in JavaScript is a fairly straight forward function. You call the function on a string, and it will return the string with all the letters capitalized.

In this post we are going to go over different use cases for the function and at the end we will build a real application which relies heavily on the .toUpperCase() function to provide its functionality.

If you simply want some easy examples on how to use .toUpperCase() then here they are.

1. Using .toUpperCase() to capitalize every word.

var sentence = "i am a sentence with lower case characters" 
sentence = sentence.toUpperCase();
console.log(sentence);

2. Using .toUpperCase() to capitalize the first letter of a string.

var sentence = "i am a sentence with lower case characters" 
sentence = sentence.charAt(0).toUpperCase() + sentence.substring(1, sentence.length -1);
console.log(sentence);

Now that we have the easy examples out of the way, lets dive into some more meaty and interesting use cases for the function. We are also going to look at how we can create our own .toUpperCase() function, so that we can capitalize words without the built in option.

Different ways to use .toUpperCase() in JavaScript

We have already seen how to capitalize the first letter of a string and how to capitalize a whole sentence using JS, so we will not go over those again. Rather, we will dive into some more complex cases that you might be interested in.

1. Capitalize the first letter of each word in a string

The first example we will look at is how we can turn the first letter of each word into an uppercase letter. The strategy here will be to first convert the string into an array, and then we will capitalize the first letter of each word in the array as we loop over it.

You could use this technique for example if you wanted to capitalize the first and last name, as it would be given as a string. “FirstName LastName”.

var sentence = "I am the sentence that we are going to work with for this example";

function capitalizeFirstLetterOfEachWord(sentence){
    var stringAsArray = sentence.split(" "); // Split on spaces
    
    for(var i = 0; i < stringAsArray.length; i++){
        stringAsArray[i] = stringAsArray[i].charAt(0).toUpperCase() 
                + stringAsArray[i].substring(1, stringAsArray[i].length);
    }

    return stringAsArray.join(" ");
}

capitalizeFirstLetterOfEachWord(sentence);

You can copy the code above into the console to play around with it. You should see the following if you do.

Code example where we capitalize the first letter of every word in a string.

This function can also be useful if you are building a website and you want to make the first letter in all the words in titles upper case automatically.

2. Capitalize every other letter

The next example we want to tackle is to capitalize every other letter in a string.

The strategy we will use here is that we will loop over each character in the string. We will not count spaces in this code example. We will determine if the letter should be upper case based on if the index we are on is even or odd (spaces don’t count so we will keep a separate index variable). For this example we are going to start by upper casing the first letter, so every odd index will be upper case.

A good exercise for you would be to modify this code so that every even index is capitalized instead.

var sentence = "A new example string we will use";

function capitalizeEveryOtherWord(sentence){
    var newSentence = "";
    var index = 1;

    for(var i = 0; i < sentence.length; i++){
        var letter = sentence.charAt(i);
        if(index % 2 != 0){
            newSentence += letter.toUpperCase();
        } else {
            newSentence += letter;
        }
  
        if(letter == " "){
            index--;
        }
        index++;
    }

    return newSentence;
}

capitalizeEveryOtherWord(sentence);

If you copy this into the console to play around with it then you should see the following.

There might not be too many real world use cases for this example, but it is a great way to explore how to work with the toUpperCase() function. A better application that is somewhat similar is that you could loop through the words to make sure that random letters are not capitalized in the middle.

3. Using .toUpperCase() to compare two strings

The idea is that we want to compare two sentences, but we only care that the content is the same, not the capitalization.

If you copy the following into the console you can see that the two words do not come back as equal, and the only difference is the capitalization of the words.

console.log("HELLO" == "hello"); // returns false
console.log("hello" == "hello"); // returns true

You often see this with user names for example. They often say they are not case sensitive, and that is because before they compare them they are processed to make them in the same form.

We can use this function to compare a string that the user gives us to a string that we have stored.

var storedString = "SECRETWORD";

function compareWord(word){
    var transformed = word.toUpperCase();
    return transformed == storedString;
}

console.log(compareWord("test")); // returns false
console.log(compareWord("secretWord")); // returns true
Code example where we use .toUpperCase() when comparing two words

As you can see, there are a few common use cases for this function.

Another potential use case is if you want to create a word editor, you could create a button that would turn all the highlighted text into upper case. You could do this by grabbing the words that are highlighted and the calling the function on that string.

Building our own version of .toUpperCase()

Having a function that capitalizes something for us is great, but sometimes we have to create our own to really understand what is going on. In this section we are going to take advantage of the ASCII table to build our own version of the .toUpperCase() function.

If you look at the ASCII table you will notice that when you convert a character to an integer, the difference between a lower case letter and an upper case letter is always 32. That means, if we want to change a lower case letter to an upper case letter, all we have to do is:

  1. Convert character to ASCII
  2. Subtract 32
  3. Convert ASCII to character

If we wanted to convert from upper case to lower case then we just have to add 32 instead of subtracting.

Lets go ahead and create our own upper case conversion function. This function will work with one or more characters, just like the original .toUpperCase() function.

var testString = "lets test it on this string";
var testCharacter = "a";

function toUpperCase(text){
    var newText = "";

    for(var i = 0; i < text.length; i++){
        var char = text.charCodeAt(i);
        newText += String.fromCharCode(char - 32);
    }
    
    return newText;
}

console.log("Test string: " + toUpperCase(testString));
console.log("Test character: " + toUpperCase(testCharacter));

That is it, we now have our own custom built function that works pretty much the same as the regular .toUpperCase() function. A great exercise for you is to modify this code so that it will do uppercase to lowercase, and perhaps do some input checking in case you want to limit the functionality to only deal with letters. Using this on other characters produces a funny output.

Building a custom application using .toUpperCase()

Now that we have looked at a lot of different use cases for capitalization, let us build an application using this function.

We want to build an auto corrector using the .toUpperCase() function. What this application will do is to make sure that every sentence is started with a capital letter. We will achieve this by scanning the text and look for periods. If we find a period then we know that is the end of the sentence, and the next letter should be a capital letter. If that letter is a lower case letter, then we will automatically convert it to upper case.

I think this is a great use of the .toUpperCase() function in a real life scenario. This could be used in an online text editor to help the user keep their grammar on point.

The application we are building need the following components

  1. A Text area for input text
  2. A text area for the corrected text
  3. A button to initiate our scanning

Now that we know what to make and how we are going to do it, lets get started.

1. Adding our HTML elements

Let us start by creating the HTML elements that we will need so that the user can interact with our application. I am going to embed this application at the bottom of this page so that you can test it out.

Text area

<textarea id="input">Here is some. default test that we. will use. new sentence. should be upper. case. </textarea>

<textarea id="output" readonly>Corrected text will go here</textarea>

Button

<button id="initiateButton">Correct Text</button>

2. Styling our Elements

We need to add a little bit of styling to our elements as well. I am embedding the application below and to make things look right we have to add the following styling.

<style> 
    textarea {
        height: 200px;
    }

    #initiateButton{
        background-color: #f2f2f2;
        display: block;
        margin: 20px 0px;
    }
</style>

3. Adding our logic using JavaScript

The steps we need to take to accomplish our goal are the following:

  1. Scan the text for periods
  2. If a period is found, then check the next character (ignore spaces)
  3. If the next character is lower case then convert it to an upper case
  4. Update the second text area
  5. Display the number of errors we found in the label

Lets get started implementing this functionality.

var button = document.getElementById("initiateButton");

button.addEventListener("click", function(){
    correctText();
});

function correctText(){
    var text = getTextFromTextArea("input");
    var corrected = processText(text);
    document.getElementById("output").innerHTML = corrected;
}

function getTextFromTextArea(id){
    return document.getElementById(id).value + '';
}

function processText(text){
    var newText = "";
    var nextShouldBeUpperCase = false;
    var currentChar = "";

    for(var i = 0; i < text.length; i++){
        var ascii = text.charAt(i).charCodeAt();

        if(text.charAt(i) == "."){
            nextShouldBeUpperCase = true;
            currentChar = text.charAt(i);
        } else if(nextShouldBeUpperCase){
           if( (ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122) ){ 
               nextShouldBeUpperCase = false; 
               currentChar= text.charAt(i).toUpperCase(); 
           } else { 
               currentChar= text.charAt(i); 
           }    
        } else {
            currentChar= text.charAt(i);      
        }

        newText += currentChar;
    }

    return newText;
}

That is all we need to implement the functionality we want.

Working Application

I hope you found this post helpful and you should now be equipped to use .toUpperCase() in any scenario you could come across.

Last Updated: by Ole Larsen