JavaScript (ES2026) reference · String Methods
JavaScript String localeCompare() Method
Compare two strings using language rules; returns a negative number, 0 or a positive number. Use it to sort names.
JavaScript (ES2026) Since ES3
Syntax
string.localeCompare(compareString, locales, options)
Parameters
| Parameter | Description |
|---|---|
compareString |
The string to compare with. |
locales optional |
A locale such as "de" or "sv". |
options optional |
For example { sensitivity: "base" } or { numeric: true }. |
Return value
Negative, zero or positive.
Examples
const names = ["Émile", "zoe", "Adam", "eve"];
console.log([...names].sort());
console.log([...names].sort((a, b) => a.localeCompare(b)));
Output
[ 'Adam', 'eve', 'zoe', 'Émile' ] [ 'Adam', 'Émile', 'eve', 'zoe' ]
const files = ["file10", "file2", "file1"];
console.log(files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));
Output
[ 'file1', 'file2', 'file10' ]
Version history
| Version | Change |
|---|---|
| JavaScript ES3 | Added |
In other languages
strcmp()· PHP
Related
string.toLowerCase()· Return the string converted to lowercase. Use it for case-insensitive comparisons.array.sort()· Sort the array in place and return it. Without a compare function elements are sorted as strings, so numbers need one.string.normalize()· Return the Unicode normalization form of a string so visually identical text compares equal (NFC, NFD, NFKC, NFKD).- JavaScript Strings · tutorial
- JavaScript String Methods · tutorial