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

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

string.localeCompare(compareString, locales, options)

Parameters

ParameterDescription
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

Sort like a human wouldTry it yourself
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' ]
Numeric-aware sortingTry it yourself
const files = ["file10", "file2", "file1"];
console.log(files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })));

Output

[ 'file1', 'file2', 'file10' ]

Version history

VersionChange
JavaScript ES3Added

In other languages

Was this page helpful?