The String toLocaleUpperCase() method
By Flavio Copes
Learn how the JavaScript toLocaleUpperCase() method returns an uppercase string using locale-specific case mappings, handy for languages like Turkish.
toLocaleUpperCase() returns a new string with the text in upper case, using the case mappings of a specific locale. Some languages uppercase letters differently, and this method respects those rules.
You pass the locale as the first parameter. If you omit it, the method uses the locale of the environment the code runs in:
'Testing'.toLocaleUpperCase() //'TESTING'
'Testing'.toLocaleUpperCase('it') //'TESTING'
'Testing'.toLocaleUpperCase('tr') //'TESTİNG'
Notice the Turkish result. The lowercase i became İ, with a dot on top.
Why does the locale matter?
For most languages, uppercase conversion is the same everywhere. a becomes A, m becomes M. The generic toUpperCase() method handles that fine, and for those languages both methods return the same result.
Turkish is the classic exception. It has two distinct letters: the dotless ı and the dotted i. Uppercasing i with Turkish rules gives İ, not I:
'istanbul'.toUpperCase() //'ISTANBUL'
'istanbul'.toLocaleUpperCase('tr') //'İSTANBUL'
The first result is wrong for a Turkish reader. It’s a different letter. If your app displays Turkish text in caps, this method is the correct tool.
How does the parameter work?
The parameter accepts a BCP 47 language tag, like 'tr' or 'de'. You can also pass an array of locales, and JavaScript uses the first one it supports:
'izmir'.toLocaleUpperCase(['tr', 'en']) //'İZMİR'
If you pass a string that isn’t a valid language tag, you get a RangeError:
'izmir'.toLocaleUpperCase('not a locale') //RangeError
Like every string method, it does not mutate the original. Strings are immutable, so you get a new string back and the original stays as it was.
Which one should you use?
Here’s the pitfall: calling toLocaleUpperCase() with no argument. The result then depends on where the code runs. The same string can uppercase differently on a Turkish user’s browser and on yours, and that inconsistency is hard to debug.
The fix is to be explicit. If you’re formatting text for a known language, pass the locale. If you’re normalizing strings for comparisons, keys, or lookups, use toUpperCase() instead, because you want the same output on every machine.
In short: toUpperCase() for logic, toLocaleUpperCase('xx') with an explicit locale for text people will read.
Related posts about js: