String.prototype.localeCompare
Compares strings by language rules — for alphabetical sorting.
Available since: ES3
Syntax
str.localeCompare(compareString, locales, options)Parameters
| Parameter | Type | Description |
|---|---|---|
| compareString | string | The string to compare with. |
| locales | string | Optional. The language whose rules are used, for example en or ru. |
| options | object | Optional. Settings such as sensitivity or numeric. |
Return value
numberA negative number, 0 or a positive number — the string comes before, equals or comes after.
Examples
The comparison result:
console.log('apple'.localeCompare('banana'));
console.log('banana'.localeCompare('apple'));
console.log('apple'.localeCompare('apple'));Output:
-1
1
0Sorting names alphabetically:
const names = ['oleg', 'Anna', 'Émile', 'boris'];
console.log(names.sort((a, b) => a.localeCompare(b)).join(', '));Output:
Anna, boris, Émile, olegNumbers inside strings are compared as numbers:
const files = ['file10', 'file2', 'file1'];
console.log(files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })).join(', '));Output:
file1, file2, file10Notes
A plain sort() without a compare function compares character codes: capitals come before lowercase letters and accented letters go to the end. localeCompare() sorts the way people expect.
See also
- Array.prototype.sort — Sorts the elements of an array.
- Intl.Collator — Compares strings by language rules — for fast alphabetical sorting.
- String.prototype.toLowerCase — Converts a string to lowercase.
Related recipes
In the tutorial
- Sorting arrays — How to sort an array in JavaScript: sort, the compare function, sorting numbers, strings and objects, reverse and toSorted.