JavaScript String toUpperCase() method is used to convert a string to uppercase letters and returns a new string with all characters in uppercase. It does not change the original string.
This method throws a TypeError when called on null or undefined.
Syntax
string.toUpperCase()
Parameters
None.
Return Value
It returns a new string where all characters are in uppercase.
Visual Representation
Example 1: How to Use String toUpperCase() Method
let str = 'Cristiano Ronaldo is a Portuguese professional footballer';
upperStr = str.toUpperCase();
console.log(upperStr);
Output
CRISTIANO RONALDO IS A PORTUGUESE PROFESSIONAL FOOTBALLER
Example 2: Using special characters and digits
let str = 'Cristiano Ron@ldo CR7';
upperStr = str.toUpperCase();
console.log(upperStr);
Output
CRISTIANO RON@LDO CR7
Similar toLowerCase(), this method only affects alphabetic characters. Digits and special characters remain unchanged.
Example 3: Converting only the First Letter of a String
To convert the first letter of a string to uppercase, you can use the “charAt()“ method together with “toUpperCase()” and then concatenate this with the rest of the string using “slice()“.
let str = "cristiano ronaldo";
str = str.charAt(0).toUpperCase() + str.slice(1);
console.log(str);
Output
Cristiano ronaldo
Example 4: Converting the First Letter of Every Word in a String
To convert the first letter of every word in a string to uppercase, you can split the string into words, converting the first letter of each word to uppercase, and then joining the words back together.
let str = "cristiano ronaldo";
str = str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
console.log(str);
Output
Cristiano Ronaldo
Browser compatibility
- Chrome version 1 and above
- Edge version 12 and above
- Firefox version 1 and above
- Opera version 3 and above
- Safari version 1 and above