inspection

String.prototype.localeCompare

Returns a negative number, 0, or a positive number indicating whether the string sorts before, equal to, or after compareString according to the current or supplied locale. Preferred over < and > for user-visible sorting.

str.localeCompare(compareString[, locales[, options]])

Parameters

Parameter Purpose
compareString String to compare against
locales BCP 47 locale tag(s), e.g. 'en', 'de'
options {sensitivity, numeric, caseFirst, ...} Intl.Collator options

Examples

console.log('a'.localeCompare('b'));

Prints -1 (or a negative number)

console.log('a'.localeCompare('A', 'en', { sensitivity: 'base' }));

Prints 0

console.log('2'.localeCompare('10', undefined, { numeric: true }));

Prints -1 (numeric sort)

console.log(['ä', 'z', 'a'].sort((x, y) => x.localeCompare(y, 'de')));

Prints [ 'a', 'ä', 'z' ]

Gotcha

Return value is only guaranteed to be negative/zero/positive — do not assume ±1. For repeated comparisons, cache an Intl.Collator instance for performance.

Related methods

← All JS string methods · JS array methods