Change JavaScript string case with deliberate locale rules

JavaScript strings are immutable. toLowerCase() and toUpperCase() return new strings. They do not change the original value.

Use locale-aware casing when the selected language changes the mapping. Do not assume casing is a reversible conversion or a complete rule for comparing arbitrary human text.

Run the conversions

Paste this code into a browser console or save it as case-demo.js and run it with Node.js:

JavaScript
const original = "Reference Note";
console.log(original.toLowerCase());
console.log(original.toUpperCase());
console.log(original);
console.log("I".toLocaleLowerCase("tr"));

The output is reference note, REFERENCE NOTE, Reference Note, then the Turkish dotless ı. The original value is unchanged.

Choose the rule for the data

For user-facing transformations, use the user's language where appropriate. For a protocol token or identifier, follow that protocol's comparison and normalization rules instead of applying a locale-sensitive operation.

Case conversion can change string length. An uppercase mapping is not necessarily one character for one character, so do not use the transformed string's indexes to address the original without accounting for that change. If the input may be null or another type, validate it before calling a string method rather than hiding invalid data with an unconditional coercion.

When the goal is linguistic sorting or comparison rather than displaying transformed text, consider Intl.Collator with explicit options. That expresses the comparison's intent without modifying the stored text.

Official references

String.prototype.toLowerCase() - JavaScript | MDN
The toLowerCase() method of String values returns this string converted to lower case.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
String.toLowerCase
String.prototype.toLocaleLowerCase() - JavaScript | MDN
The toLocaleLowerCase() method of String values returns this string converted to lower case, according to any locale-specific case mappings.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase
Locale-aware casing

Author: Herman Schoenfeld