This concise article shows you how to convert a string to upper or lower case in JavaScript, from theory to practical examples.
Overview
To convert a given string to uppercase, you can use the toUpperCase() method. To convert a string to lowercase, you can use the toLowerCase() method. Both of these methods return a new string with the case converted as desired (the original string is intact).
Examples
Converting a string to uppercase
The code:
const name = "welcome to sling academy";
const upperCaseName = name.toUpperCase();
console.log(upperCaseName);
Output:
WELCOME TO SLING ACADEMY
Converting a string to lowercase
The code:
const message = "THE DRAGON IS FLYING OVER THE MOUNTAIN";
const lowerCaseMessage = message.toLowerCase();
console.log(lowerCaseMessage);
Output:
the dragon is flying over the mountain
Using a user input
The code:
const userInput = prompt("Enter a string:");
const upperCaseInput = userInput.toUpperCase();
console.log(upperCaseInput);
Run this code with a web browser and see how it works.
Using the ternary operator
The code:
const greeting = 'one more time, bad moon rising';
const isUpperCase = true;
const formattedGreeting = isUpperCase
? greeting.toUpperCase()
: greeting.toLowerCase();
console.log(formattedGreeting);
Output:
ONE MORE TIME, BAD MOON RISING