The String toLowerCase() method

By

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

~~~

toLowerCase() returns a new string with all the text in lower case. It does not mutate the original string, and it does not accept any parameter.

Usage:

'Testing'.toLowerCase() //'testing'

Characters that have no lower case version, like numbers and punctuation, stay as they are:

'Room 42!'.toLowerCase() //'room 42!'

The original string never changes

Strings in JavaScript are immutable. toLowerCase() gives you a new string, and the one you called it on stays the same:

const name = 'Flavio'
const lower = name.toLowerCase()

name //'Flavio'
lower //'flavio'

If you want to keep the lower case version, assign it to a variable, like we did with lower. Calling the method and throwing away the result does nothing.

When do you reach for it?

The most common use is comparing strings without caring about case. Say a user types their email with some capital letters. Normalize both sides before comparing:

const typed = 'Flavio@Gmail.com'
const stored = 'flavio@gmail.com'

typed === stored //false
typed.toLowerCase() === stored //true

The same trick works for searching. Lower-case both the input and the values you search through, and 'Rome' matches 'rome':

const input = 'Rome'
const cities = ['rome', 'milan', 'florence']

cities.includes(input.toLowerCase()) //true

A pitfall to watch for

toLowerCase() only exists on strings. If your variable is undefined or null, calling it throws:

let city
city.toLowerCase() //TypeError: Cannot read properties of undefined

This bites hard when the value comes from user input or an API response that might be missing. Check the value first:

if (typeof city === 'string') {
  city.toLowerCase()
}

Or use optional chaining, which returns undefined instead of throwing:

city?.toLowerCase() //undefined

What about other languages?

Works similarly to toLocaleLowerCase(), but does not consider locales at all.

For most text the two return the same result. A few languages have special casing rules, like Turkish with its dotted and dotless i. If you handle text in those languages, use toLocaleLowerCase() and pass the locale. For everything else, toLowerCase() is the one you want.

Tagged: JavaScript ยท All topics
~~~

Related posts about js: