In JavaScript, we can convert a string to uppercase by using the JavaScript String toUpperCase() method.
"This is Some Text".toUpperCase();
When working with strings, it can be useful to convert a string to uppercase. A lot of the time when comparing strings, you will need to convert them both to either uppercase or lowercase to compare them since most comparison operators are case sensitive.
In JavaScript, we can easily convert a string to uppercase using the toUpperCase() method.
Converting a String to Uppercase In JavaScript with a Click
In this simple example, we will let the user input a string, and we will convert it to uppercase.
Here is the HTML setup:
Convert to Uppercase
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 string to uppercase using the String toUpperCase() method.
We will finally post the results using the textContent property.
function stringToUppercase(){
//Get the user string
var userString = document.getElementById("string1").value;
//Convert the string to uppercase
var uppercaseString = userString.toUpperCase();
//Display the results
document.getElementById("results").textContent = uppercaseString;
}
The final code and output for converting a string to uppercase in JavaScript is below.
Code Output:
Full Code:
Convert to Uppercase
<script>
function stringToUppercase(){
var userString = document.getElementById("string1").value;
var uppercaseString = userString.toUpperCase();
document.getElementById("results").textContent = uppercaseString;
}
</script>
Hopefully this article has been useful for you to learn how to use JavaScript to convert a string to uppercase.