String.prototype.localeCompare()
Compares two strings in the current or specified locale, returning sort order.
Syntax
str.localeCompare(compareString, locales, options) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
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
| Environment | Since version |
|---|---|
| chrome | 1.0 |
| firefox | 1.0 |
| safari | 1.0 |
| edge | 12 |
| node | 0.10 |