Skip to main content
Version: 3.13.0

String.prototype.localeCompare()

The 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. In implementations with Intl.Collator API support, this method simply calls Intl.Collator.

Syntax

localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

Parameters

The locales and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.

In implementations that support the Intl.Collator API, these parameters correspond exactly to the Intl.Collator() constructor's parameters. Implementations without Intl.Collator support are asked to ignore both parameters, making the comparison result returned entirely implementation-dependent — it's only required to be consistent.

  • compareString

    • : The string against which the referenceStr is compared.
  • 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.

      In implementations without Intl.Collator support, this parameter is ignored and the host's locale is usually used.

  • options optional

    • : An object adjusting the output format. Corresponds to the options parameter of the Intl.Collator() constructor.

      In implementations without Intl.Collator support, this parameter is ignored.

See the Intl.Collator() constructor for details on the locales and options parameters and how to use them.

Return value

A negative number if referenceStr occurs before compareString; positive if the referenceStr occurs after compareString; 0 if they are equivalent.

In implementations with Intl.Collator, this is equivalent to new Intl.Collator(locales, options).compare(referenceStr, compareString).

Description

Returns an integer indicating whether the referenceStr comes before, after or is equivalent to the compareString.

  • Negative when the referenceStr occurs before compareString
  • Positive when the referenceStr occurs after compareString
  • Returns 0 if they are equivalent

Warning: Do not rely on exact return values of -1 or 1!

Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value.

Performance

When comparing large numbers of strings, such as in sorting large arrays, it is better to create an Intl.Collator object and use the function provided by its compare() method.