JavaScript toLocaleUpperCase() method


The toLocaleUpperCase() method in JavaScript is used to convert a string to uppercase, taking into account locale-specific rules for case conversion. This method is particularly useful for languages that have unique casing rules, such as Turkish, where the uppercase representation of certain letters can differ from that in other languages.

Syntax:

string.toLocaleUpperCase([locale])
  • locale (optional): A string with a BCP 47 language tag that represents the locale. If omitted, the method defaults to the runtime's current locale.

Return Value:

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

Example 1: Basic Usage

let str = "Hello, World!"; let upperStr = str.toLocaleUpperCase(); 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: Locale-Specific Uppercase Conversion

The toLocaleUpperCase() method is particularly useful when dealing with languages that have specific casing rules.

let str = "istanbul"; // Turkish lowercase 'i' let upperStr = str.toLocaleUpperCase('tr-TR'); // Turkish locale console.log(upperStr); // "Ä°STANBUL" (correct Turkish uppercase)

In this case, the lowercase 'i' is converted to the uppercase 'Ä°', which is the correct representation in Turkish, where the dot on the 'i' is important.

Example 3: Using Different Locales

You can specify different locales to see how they handle the conversion.

let str1 = "some text"; let str2 = "istanbul"; console.log(str1.toLocaleUpperCase('en-US')); // "SOME TEXT" (English locale) console.log(str2.toLocaleUpperCase('tr-TR')); // "Ä°STANBUL" (Turkish locale)

Here, the method handles the lowercase letters according to the rules of the specified locale.

Example 4: Original String Remains Unchanged

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

let str = "Hello, World!"; let upperStr = str.toLocaleUpperCase(); console.log(str); // "Hello, World!" (original string remains unchanged) console.log(upperStr); // "HELLO, WORLD!" (new uppercase string)

Summary:

  • The toLocaleUpperCase() method converts all characters in a string to uppercase based on locale-specific rules.
  • It returns a new string without modifying the original string.
  • If no locale is specified, it defaults to the current runtime's locale.
  • This method is particularly useful for correctly handling string casing in languages with unique casing rules, ensuring accurate and culturally appropriate string manipulation.