Press ESC to close

toUpperCase

0 1763

JavaScript toUpperCase is a method when it is useful to want to turn all text into uppercase.

This method can be applied to a string and has the following syntax:

string.toUpperCase();

In this short tutorial we will give examples of using this method in order to learn how to use it correctly.

toUppercase – first example

Check if a string is capitalized or not.

First we initialize a string variable. For example, I assigned the creative coding value.

Then we verify the condition: does the string match the same string written in uppercase? If this condition is true then we write the sentence ‘the string is already written in uppercase’, otherwise we transform it into uppercase and display the transformed string.

Here is an example of using the if else conditional statement and the JavaScript toUpperCase method.



 var string = 'Coding Creativo';

 if (string == string.toUpperCase()){
    document.write('The string is already capitalized ' + coding);
 } else {
   string = string.toUpperCase();
   document.write('The transformed string is: ' + stringa);
}

toUppercase – second example with getElementById

Enter a value through an input field and, after clicking on ok, we transform this value into uppercase.

In this example, in addition to JavaScript’s toUpperCase method, we will also use the getElementById method that we explained in this tutorial: getElementById method.

Therefore, remember that this method returns the element that has the id equal to the one specified in round brackets.

By clicking on the ok button, we call the function transform () in JavaScript.

So here is the html code:

<h1>Example with the toUpperCase and getElementById method</h1>
<label>Insert the name: </label>
<input type="text" id="name">
<input type="button" id="ok" value="ok" onclick="transform()">
<p id="result"></p>

And JavaScript code:



function transform() {
   var name = document.getElementById("name").value;
   name = name.toUpperCase();
   document.getElementById("result")
    .innerHTML = "The name is: " + nome;
}

Conclusion

In this lesson, we used JavaScript’s simple method, toUpperCase, to capitalize text. Later we will deal with many other examples and in particular we will see how to transform for example only the first letter in uppercase and everything else in lowercase.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Other stories

toLowerCase JavaScript

Next Story

JavaScript console log

Previous Story