localeCompare

The localeCompare task compares two strings in the current locale and returns a numeric value (negative, zero, or positive) indicating whether the reference string comes before, after, or is the same as the compareString in sort order. The locale is based on the language settings of the browser.

Potential use case

Use this task to sort an array of strings with special characters, or to implement “natural sorting” in which numbers embedded in strings are treated numerically (sorted low to high). The task also provides multiple options to control how certain formatting conventions are handled when sorting.

Properties

InputTypeRequiredDescription
referenceStrStringYesThe reference string to compare.
compareStringStringYesThe string to compare against referenceStr.
localesStringNoA BCP 47 language tag string, or an array of such tags. If not provided, the default locale is used. Allowed Unicode extension keys are "co", "kn", and "kf".
optionsObjectNoOptions to apply to the sort order. The options object may include: "caseFirst", "ignorePunctuation", "localeMatcher", "numeric", "sensitivity", and "usage".
OutputTypeDescription
compareResultNumberA number indicating the sort relationship. Returns -1 (negative) when the reference string appears before compareString; 0 if the two strings are equal; 1 (positive) when the reference string appears after compareString. Do not rely on exact return values of -1 or 1 — negative and positive values vary between browsers and versions.

Example 1

In this example, referenceStr is "Hello World" and compareString is "héllö wôrld" (with an acute accent on é, a diaeresis on ö, and a circumflex on ô).

localeCompare task with referenceStr 'Hello World' and compareString 'héllö wôrld'

The compareResult is -1 (negative) because the reference string comes before the comparison string.

Output showing compareResult as -1

Example 2

In this example, referenceStr is "8" and compareString is "30".

localeCompare task with referenceStr '8' and compareString '30'

The compareResult is 1 (positive) because the string value "8" comes after "30" in string sort order.

Output showing compareResult as 1

Example 3

In this example, referenceStr is "réservé" (with acute accents) and compareString is "reserve" (no accents). The locales option is set to "en" (English), and options includes "sensitivity": "base" to indicate the strings do not have the same base letters.

localeCompare task with réservé vs reserve, locales en, and sensitivity base

The compareResult is 0 because the two strings are considered equal under these settings.

Output showing compareResult as 0

See the Intl.Collator constructor on MDN for more information on the locales and options parameters.