How to convert string to upper and lowercase in JavaScript

Converting strings to lowercase

In JavaScript, we can use the toLowerCase method to convert a string into a lowercase string. The toLowerCase method will return a new string.

var str = "UPPER Case";
var lowerCaseStr = str.toLowerCase();
console.log(lowerCaseStr);

Converting strings to uppercase

In JavaScript, we can also use the toUpperCase method to convert a string into an uppercase string. The toUpperCase method will return a new string.

var str = "uppercase";
var upperCaseStr = str.toUpperCase();
console.log(upperCaseStr);

Capitalize a string

We don’t have any in-build method to capitalize a string. However, we can implement our own method. The steps to capitalize a string are:

  • Convert the string to lowercase
  • Replace the first letter with an uppercase letter
function capitalize(str) {
const lowerCaseString = str.toLowerCase(), // convert string to lower case
firstLetter = str.charAt(0).toUpperCase(), // upper case the first character
strWithoutFirstChar = lowerCaseString.slice(1); // remove first character from lower case string
return firstLetter + strWithoutFirstChar;
}
console.log(capitalize("javaScript"));
console.log(capitalize("educative.io"));