Code Logo

Convert Case with toUpperCase()

Published at25 Jul 2026
JavaScript String Handling Easy 0 views
Like0

Write a JavaScript function that takes a string and a mode ("upper" or "lower") and returns the string converted to uppercase or lowercase accordingly using toUpperCase() or toLowerCase().

String.prototype.toUpperCase() returns the calling string value converted to uppercase. String.prototype.toLowerCase() returns the calling string value converted to lowercase. Both methods do not modify the original string because JavaScript strings are immutable — they return a new string.

These methods perform Unicode case mapping, not just simple ASCII case changes. This means they correctly handle accented characters (é → É), special Unicode characters (ß → SS in German), and locale-specific mappings. However, for locale-sensitive mappings like Turkish I (dotless i), the methods may not always produce the expected result.

Time complexity is O(n) where n is the string length. Space complexity is O(n) for the new string. The methods create a new string with the same length as the original, plus potentially different byte length for Unicode characters that expand during case conversion.

Edge cases include empty strings (returns empty string), strings with no alphabetic characters (unchanged), mixed-case strings, Unicode characters, and ensuring the correct method is called based on the mode parameter.

Example Input & Output

Example 1
Input
"hello","upper"
Output
"HELLO"
Explanation

Convert to uppercase

Example 2
Input
"WORLD","lower"
Output
"world"
Explanation

Convert to lowercase

Example 3
Input
"abc","upper"
Output
"ABC"
Explanation

Simple uppercase

Example 4
Input
"JavaScript","lower"
Output
"javascript"
Explanation

Mixed case to lower

Example 5
Input
"JavaScript","upper"
Output
"JAVASCRIPT"
Explanation

Mixed case to upper

Algorithm Flow

Recommendation Algorithm Flow for Convert Case with toUpperCase()
Recommendation Algorithm Flow for Convert Case with toUpperCase()

Solution Approach

function solution(str, mode) {
  if (mode === 'upper') return str.toUpperCase();
  return str.toLowerCase();
}

Best Answers

javascript - Approach 1
function solution(str, mode) {
  if (mode === 'upper') return str.toUpperCase();
  return str.toLowerCase();
}