JavaScript toUpperCase() method


The toUpperCase() method in JavaScript is used to convert all the characters in a string to uppercase. This method is useful when you want to standardize string data for display or comparison purposes.

Syntax:

string.toUpperCase()

Return Value:

  • Returns a new string with all the characters converted to uppercase. The original string remains unchanged.

Example 1: Basic Usage

let str = "Hello, World!"; let upperStr = str.toUpperCase(); console.log(upperStr); // "HELLO, WORLD!"

In this example, the method converts the string "Hello, World!" to "HELLO, WORLD!", changing all lowercase letters to their uppercase equivalents.

Example 2: Handling Mixed Case

The toUpperCase() method works on strings with mixed case.

let str = "JaVaScRiPt Is AwEsOmE!"; let upperStr = str.toUpperCase(); console.log(upperStr); // "JAVASCRIPT IS AWESOME!"

Here, all letters in the string are converted to uppercase.

Example 3: Original String Remains Unchanged

The original string is not modified by the toUpperCase() method.

let str = "hello, world!"; let upperStr = str.toUpperCase(); console.log(str); // "hello, world!" (original string remains unchanged) console.log(upperStr); // "HELLO, WORLD!" (new uppercase string)

Example 4: Non-Alphabetic Characters

Non-alphabetic characters remain unchanged when using toUpperCase().

let str = "123 abc! @#"; let upperStr = str.toUpperCase(); console.log(upperStr); // "123 ABC! @#"

In this example, the numbers and special characters stay the same, while the letters are converted to uppercase.

Example 5: Locale Considerations

The toUpperCase() method is case-sensitive and follows the default locale of the environment. For certain characters, the uppercase representation may differ based on the locale.

let str = "istanbul"; // Turkish 'i' let upperStr = str.toUpperCase(); console.log(upperStr); // "ISTANBUL" (standard uppercase)

In this case, the lowercase 'i' is converted to the uppercase 'I', which is the standard representation.

Summary:

  • The toUpperCase() method converts all characters in a string to uppercase.
  • It does not change the original string; it returns a new string with the uppercase conversion.
  • Non-alphabetic characters are unaffected by the method.
  • The method's behavior can depend on the default locale, particularly for special characters.