String.prototype.localeCompare()

Compares two strings in the current or specified locale, returning sort order.

Since ES1 Spec ↗

Syntax

str.localeCompare(compareString, locales, options)

Parameters

NameTypeRequiredDescription
compareString string Yes The string to compare against.
locales string | string[] No A BCP 47 language tag or array of tags.
options object No Intl.Collator options such as sensitivity, numeric, and caseFirst.

Returns

number — Negative if str sorts before, positive if after, 0 if equal.

Examples

console.log('a'.localeCompare('b'));
Output
-1
console.log('2'.localeCompare('10', undefined, { numeric: true }));
Output
-1

Notes

The exact magnitude (often -1/0/1) is implementation-defined; only the sign is meaningful. Use the `numeric` option for natural numeric ordering. Slower than `<`/`>` - for heavy sorting use `Intl.Collator`.

Browser & runtime support

EnvironmentSince version
chrome 1.0
firefox 1.0
safari 1.0
edge 12
node 0.10

See also