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
String.prototype.normalize
Returns the Unicode Normalization Form of the string ('NFC', 'NFD', 'NFKC', or 'NFKD'; default 'NFC'). Essential for reliable comparison of characters that can be represented in multiple code point sequences.
String.prototype.toLowerCase
Returns a new string with all characters converted to lower case using Unicode default case mapping. For locale-specific behavior use toLocaleLowerCase.
String.prototype.toUpperCase
Returns a new string with all characters converted to upper case using the Unicode default case mapping. Locale-insensitive — use toLocaleUpperCase for language-specific rules (e.g. Turkish i).
String.prototype.length
Read-only property giving the number of UTF-16 code units in the string. Not the number of visible characters — emoji and combining marks can inflate the count.