JavaScript String.prototype.localeCompare() Method
The localeCompare() method compares two strings according to the rules of a language, for correct alphabetical sorting.
Description
The localeCompare() method returns a number showing whether the string comes before, after or in the same position as another in a language's sort order. It's the usual compare function for sorting text: arr.sort((a, b) => a.localeCompare(b)).
It handles accents and case sensibly, and the numeric option sorts numbers inside text naturally. When sorting large arrays, an Intl.Collator is faster.
It returns 0 for strings that are equivalent under the chosen options, which makes it handy for case- and accent-insensitive equality checks: a.localeCompare(b, undefined, { sensitivity: 'base' }) === 0. The exact negative or positive number returned can vary, so only check its sign.
Syntax
string.localeCompare(compareString)
string.localeCompare(compareString, locales, options)Parameters
- compareStringThe string to compare with.
- localesOptional. A language tag such as
"de". - optionsOptional. The same options as
Intl.Collator, such asnumericandsensitivity.
Return Value
A negative number if the string comes first, a positive number if it comes after, or 0 if they are equivalent.
Example
Browser Support
The following information will show you the current browser support for the String.prototype.localeCompare() method. Hover over a browser icon to see the version that first introduced support for this method.
Desktop





Tablets & Mobile





