The String toUpperCase() method

By

Learn how the JavaScript toUpperCase() method returns a new string with all the text in upper case, without mutating the original or taking any parameter.

~~~

toUpperCase() returns a new string with all the text converted to upper case. It takes no parameters:

'Testing'.toUpperCase() //'TESTING'

Characters that have no uppercase version stay as they are. Numbers, punctuation, and spaces are untouched:

'order #42, please'.toUpperCase() //'ORDER #42, PLEASE'

If you call it on an empty string, you get an empty string back.

Does it change the original string?

No. Strings in JavaScript are immutable, so no string method can change them. toUpperCase() returns a new string:

const city = 'milan'
const shout = city.toUpperCase()

city //'milan'
shout //'MILAN'

This is the pitfall I see most often. You call the method and expect the variable to change:

let name = 'flavio'
name.toUpperCase()
name //'flavio', nothing happened

The returned value was thrown away. The fix is to assign the result:

name = name.toUpperCase()
name //'FLAVIO'

When would you use it?

A common use case is comparing strings without caring about case. User input rarely arrives in a predictable case, so you normalize both sides first:

const answer = 'Yes'

if (answer.toUpperCase() === 'YES') {
  //this runs
}

Another one is display formatting, like showing a country code or a ticker symbol in caps regardless of how it was stored.

Note that if the value might not be a string, convert it first. Calling toUpperCase() on null, undefined, or a number throws a TypeError:

const code = 123
String(code).toUpperCase() //'123'

What about other languages?

toUpperCase() uses the default Unicode case mappings, ignoring the user’s locale. For English and most languages that’s exactly what you want.

Some conversions produce more characters than you started with. The German ß becomes SS, so the result can be longer than the original:

'straße'.toUpperCase() //'STRASSE'

A few languages have special rules that toUpperCase() does not apply. Turkish is the usual example: the lowercase i should become a dotted İ, not I. If you need that behavior, use toLocaleUpperCase() and pass the locale. For everything else, toUpperCase() is the one to reach for.

~~~

Related posts about js: