Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

String.prototype.localeCompare

Compares strings by language rules — for alphabetical sorting.

Available since: ES3

Syntax

str.localeCompare(compareString, locales, options)

Parameters

ParameterTypeDescription
compareStringstringThe string to compare with.
localesstringOptional. The language whose rules are used, for example en or ru.
optionsobjectOptional. 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
0

Sorting names alphabetically:

const names = ['oleg', 'Anna', 'Émile', 'boris'];
 
console.log(names.sort((a, b) => a.localeCompare(b)).join(', '));

Output:

Anna, boris, Émile, oleg

Numbers 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, file10

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.