0
0
JavascriptHow-ToBeginner · 2 min read

JavaScript How to Convert String to Uppercase

Use the toUpperCase() method on a string to convert it to uppercase, like str.toUpperCase().
📋

Examples

Inputhello
OutputHELLO
InputJavaScript
OutputJAVASCRIPT
Input123abc!
Output123ABC!
🧠

How to Think About It

To convert a string to uppercase, think of changing every letter to its capital form. The toUpperCase() method does this by scanning the string and replacing each lowercase letter with its uppercase version, leaving other characters unchanged.
📐

Algorithm

1
Get the input string.
2
Call the <code>toUpperCase()</code> method on the string.
3
Return the new uppercase string.
💻

Code

javascript
const str = 'Hello World!';
const upperStr = str.toUpperCase();
console.log(upperStr);
Output
HELLO WORLD!
🔍

Dry Run

Let's trace 'Hello World!' through the code

1

Original string

str = 'Hello World!'

2

Convert to uppercase

upperStr = str.toUpperCase() -> 'HELLO WORLD!'

3

Print result

console.log(upperStr) outputs 'HELLO WORLD!'

StepString Value
1Hello World!
2HELLO WORLD!
3HELLO WORLD!
💡

Why This Works

Step 1: Using toUpperCase()

The toUpperCase() method creates a new string with all letters converted to uppercase.

Step 2: Original string unchanged

The original string remains the same because strings are immutable in JavaScript.

Step 3: Non-letter characters

Characters like numbers and symbols are not changed by toUpperCase().

🔄

Alternative Approaches

Using a loop and manual conversion
javascript
const str = 'Hello';
let result = '';
for (const char of str) {
  const upperChar = char >= 'a' && char <= 'z' ? String.fromCharCode(char.charCodeAt(0) - 32) : char;
  result += upperChar;
}
console.log(result);
This manually converts letters but is longer and less readable than <code>toUpperCase()</code>.
Using locale-aware toLocaleUpperCase()
javascript
const str = 'i';
console.log(str.toLocaleUpperCase('tr'));
Handles locale-specific uppercase rules, useful for languages like Turkish.

Complexity: O(n) time, O(n) space

Time Complexity

The method processes each character once, so time grows linearly with string length.

Space Complexity

A new string is created to hold the uppercase result, so space also grows linearly.

Which Approach is Fastest?

toUpperCase() is optimized and fastest for general use; manual loops are slower and more error-prone.

ApproachTimeSpaceBest For
toUpperCase()O(n)O(n)Simple and fast uppercase conversion
Manual loop conversionO(n)O(n)Learning or custom logic but slower
toLocaleUpperCase()O(n)O(n)Locale-specific uppercase rules
💡
Use toUpperCase() for simple uppercase conversion in JavaScript.
⚠️
Trying to assign the result back to the original string without storing it, since strings are immutable.