String localeCompare() method

Find all information about the JavaScript localeCompare() method of the string

This method compares a string with another string and returns a number (negative number, 0, positive number), which indicates whether the current string is less than, equal to, or greater than the string passed according to the locale.

The locale is determined by the current locale, or you can pass it as the second parameter:

'a'.localeCompare('à') //-1
'a'.localeCompare('à', 'it-IT') //-1

The most common use case is to sort an array:

['a', 'b', 'c', 'd'].sort((a, b) => a.localeCompare(b))

Where people usually use it

['a', 'b', 'c', 'd'].sort((a, b) => (a > b) ? 1 : -1)

The difference is thatlocaleCompare()Allows us to make it compatible with the letters used worldwide.

The object passed as the third parameter can be used to pass other options. Find all possible values of these optionsOn MDN.

Download mine for freeJavaScript beginner's manual

More js tutorials: