This article explains how to change case to lowercase and uppercase in Javascript.
Javascript has two methods to change a string to lowercase and uppercase, called toLowerCase() and toUpperCase(), respectively.
The toLowerCase()
The toLowerCase()
is a built-in method that returns the calling string value converted to lowercase.
The following Javascript code is an example of the use of toLowerCase()
method:
<!DOCTYPE html>
<html>
<head>
<title>toLowerCase Javascript</title>
<script>
function convertStr(){
var str = "UPPERCASE";
var res = str.toLowerCase();
document.getElementById("result").innerHTML = res
}
</script>
</head>
<body>
<button onclick="convertStr()"> Convert to Lower Case </button>
<p id="result"></p>
</body>
</html>
Output:

The toUpperCase()
The toUpperCase()
is a built-in method that returns the calling string value converted to uppercase.
The following Javascript code is an example of the use of toUpperCase()
method:
<!DOCTYPE html>
<html>
<head>
<title>toLowerCase Javascript</title>
<script>
function convertStr(){
var str = "lowercase";
var res = str.toUpperCase();
document.getElementById("result").innerHTML = res
}
</script>
</head>
<body>
<button onclick="convertStr()"> Convert to Upper Case </button>
<p id="result"></p>
</body>
</html>
Output:

How to Uppercase the First Letter of a String in Javascript
Method toUpperCase()
will convert the whole characters in a string to uppercase.
Sometimes we only want to uppercase only the first letter of a string.
Uppercase Only The First Letter of a String
To uppercase only the first letter of a string in Javascript, we could use toUpperCase()
and slice()
method as follows:
<!DOCTYPE html>
<html>
<head>
<title>toLowerCase Javascript</title>
<script>
function CapsFirstLetter(){
var str = "how to capitalize only the first letter";
var res = str[0].toUpperCase() + str.slice(1);
document.getElementById("result").innerHTML = res
}
</script>
</head>
<body>
<button onclick="CapsFirstLetter()"> Capitalize First Letter </button>
<p id="result"></p>
</body>
</html>
Output:

The str[0].toUpperCase()
will uppercase the first letter of the word “how”, which is “h” letter in the “how to capitalize only the first letter” string.
And str.slice(1)
is a method to slice a string according to the passed parameters.
slice(start, end)
has two parameters. The first parameter (start) is required. It specifies the position where to begin the slicing.
The second parameter (end) is an optional parameter. It specifies the position to end the slicing. If this parameter is omitted, it selects all characters from the start.
The string index starts at position 0.
So str.slice(1)
means slicing the string starting from index 1 to last index since the second parameter is omitted.
Leave a Reply