JavaScript String localeCompare() method
returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.

syntax

localeCompare(compareString, locales, options)

compareString The string against which the reference string is compared. All values are coerced to strings.

locales (optional). A string with a BCP 47 language tag, or an array of such strings.

Corresponds to the locales parameter of the Intl.Collator() constructor.

options (optional). An object adjusting the output format.

Corresponds to the options parameter of the Intl.Collator() constructor.

localeCompare() method compares the two strings in the current locale or a specified locale.

current locale is based on the language settings of the browser.

localeCompare() method returns sort order -1, 1, or 0 (for before, after, or equal).

Warning: Do not rely on exact return values of -1 or 1, different browsers may return -2 or 2.

Returns negative number if myString appears before compareString in the sort order.

Returns positive number if myString appears after compareString in the sort order.

Returns 0 if myString is equivalent to compareString and so appears at the same position in the sort order.

The results provided by localeCompare() vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the locales argument ↴

console.log('ä'.localeCompare('z', 'de-DE')); // a negative value: in German, ä sorts before z

console.log('ä'.localeCompare('z', 'sv-SE')); // a positive value: in Swedish, ä sorts after z

The results provided by localeCompare() can be customized using the options argument.

syntax 1 description
compare myString with compareString in the current locale
myString.localeCompare(compareString)
syntax 2 description
compare myString with compareString in specified locale
myString.localeCompare(compareString, locales)
syntax 3 description
compare myString with compareString in specified locale with options to specify the behaviour of the method
myString.localeCompare(compareString, locales, options)